You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular Material 19主题中添加扩展颜色调色板

Angular Material 19(M3主题)添加扩展颜色调色板的正确方法

在Angular Material 19的Material Design 3(M3)主题体系中,info、success、warning这类扩展颜色不能直接与primary、tertiary同级放在color配置下,需要嵌套在color.extended属性中。这是因为M3主题的配置结构做了明确划分,基础色与扩展色属于不同层级。

正确的主题配置代码

修改你的style.scss,将扩展色移至extended字段内:

@use '@angular/material' as mat;
@use './_theme-colors.scss' as theme-colors;

html {
  color-scheme: light;
  @include mat.theme(
    (
      color: (
        primary: theme-colors.$primary-palette,
        tertiary: theme-colors.$tertiary-palette,
        // 扩展色需要放在extended子对象中
        extended: (
          info: theme-colors.$info-palette,
          success: theme-colors.$success-palette,
          warning: theme-colors.$warning-palette,
        )
      ),
      typography: Roboto,
      density: 0,
      high-contrast: high-contrast-overrides(light),
    )
  );
}

确保扩展色调色板符合M3格式

在_theme-colors.scss中,扩展色的调色板需要使用M3的调色板生成方式,比如用mat.define-palette基于M3颜色值定义:

@use '@angular/material' as mat;

// 示例:定义info调色板
$info-palette: mat.define-palette(
  mat.$blue-palette, // 基于M3内置的蓝色调色板
  default: 500,
  lighter: 100,
  darker: 700
);

// success、warning调色板同理
$success-palette: mat.define-palette(mat.$green-palette);
$warning-palette: mat.define-palette(mat.$amber-palette);

$primary-palette: mat.define-palette(mat.$indigo-palette);
$tertiary-palette: mat.define-palette(mat.$pink-palette);

在组件中使用扩展色

如果需要在组件样式中引用这些扩展色,可以通过主题上下文获取:

@use '@angular/material' as mat;

.my-info-button {
  background-color: mat.get-color-from-theme(mat.get-current-theme(), 'info');
  color: mat.get-color-from-theme(mat.get-current-theme(), 'info', 'contrast');
}

内容的提问来源于stack exchange,提问作者zer09

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 10:08:21