如何使用Angular Material主题调色板

3

我对实际上开始使用预安装的Angular Material主题有多么困难以及关于此方面的教程有多少感到震惊。我正试图使用官方文档中所解释的函数来使用我的主题中的值:

https://material.angular.io/guide/theming-your-components

然而,当我尝试运行这段代码时

@use 'sass:map'
@use '@angular/material' as mat

@import './styles/normalize.css'
@import 'ag-grid-community/styles/ag-grid.css'
@import 'ag-grid-community/styles/ag-theme-material.css'

$my-palette: mat.define-palette(mat.$primary-palette)

我收到了一个SASS错误,说$theme未定义。错误在哪里?


你能提供一些代码块吗? - Parth M. Dave
1个回答

3
哦,是的。如果你想要为你的材料应用程序设置样式,那么这将非常棘手。首先,为了更好地理解需要做什么,请查看材料设计师:链接。通过它,您可以创建自定义样式。
第二点:这里是Academind的一个很好的视频教程。在这里,您可以学习要做什么,并检查您链接的所有文档。您需要做的所有事情都在这个文档中。但是它写得非常混乱。因此,这个视频会有所帮助!
但是这里有一个快速指南:
  1. 首先创建一个新文件(例如my-theme.scss)
  2. 在主题文件内添加:
@use '@angular/material' as mat;

@include mat.core();

$my-primary: mat.define-palette(mat.$indigo-palette, 500);
$my-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400);

$my-theme: mat.define-light-theme((
 color: (
   primary: $my-primary,
   accent: $my-accent,
 ),
 density: 0,
));

// Emit theme-dependent styles for common features used across multiple components.
@include mat.core-theme($my-theme);

// Emit styles for MatButton based on `$my-theme`. Because the configuration
// passed to `define-light-theme` omits typography, `button-theme` will not
// emit any typography styles.
@include mat.button-theme($my-theme);

// Include the theme mixins for other components you use here.

好的,现在打开angular.json文件并进入“styles”部分。您要在“input”属性中找到类似于“node_modules/@angular/material/prebuilt-themes/.......”的内容。 enter image description here 用您的主题替换它:

enter image description here

然后重新启动您的应用程序(因为我们更改了angular.json,请再次调用ng serve)。这样它也会正常工作!

1
谢谢您的时间和完美的解释!我喜欢使用Angular,但不幸的是,我觉得一些文档部分写得很差。谢谢! - Damian Kowalski
我们必须创建自己的主题才能访问$theme吗?这似乎不太对(并不是说你的答案是错误的)。它只是感觉...不对。 - Sebastian Busek
是的,看起来很不正常,很疯狂。但在材料设计中,生成的样式文件是预先生成的css。因此,是的,您需要使用自己的主题,因为css没有任何功能等。 - Flo
1
这真的是这样吗?我的意思是,我认为 Material Design 使用 Sass,因此最终的 CSS 是在构建时生成的,所以我不太明白为什么 MDA 不将 $theme 导出为全局变量。但是我们会看到 Material Design v3 Web 推出后会发生什么。 - Sebastian Busek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接