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

Angular Material 16升级后自定义颜色调用方法咨询

Angular Material 16 自定义主题中修改.sg-text-color颜色的正确用法

Angular Material 16 切换到了Sass模块系统,旧的mat-palette、mat-color函数被新的模块API替代,下面是适配后的完整写法:

1. 定义自定义调色板与主题

@use '@angular/material' as mat;

// 自定义主调色板(完全自定义或基于官方调色板扩展)
$mat-cbh-primary: mat.define-palette(
  // 若基于官方调色板扩展,比如靛蓝
  mat.$indigo-palette,
  default: 600, // 默认色调
  lighter: 100,
  darker: 900
  // 若是完全自定义调色板,替换为以下对象:
  // (
  //   50: #e3f2fd,
  //   100: #bbdefb,
  //   200: #90caf9,
  //   300: #64b5f6,
  //   400: #42a5f5,
  //   500: #2196f3,
  //   600: #1e88e5,
  //   700: #1976d2,
  //   800: #1565c0,
  //   900: #0d47a1,
  //   contrast: (
  //     50: #000000,
  //     100: #000000,
  //     200: #000000,
  //     300: #000000,
  //     400: #ffffff,
  //     500: #ffffff,
  //     600: #ffffff,
  //     700: #ffffff,
  //     800: #ffffff,
  //     900: #ffffff
  //   )
  // )
);

// 定义浅色主题
$cbh-light-theme: mat.define-light-theme((
  color: (
    primary: $mat-cbh-primary,
    // 可选:添加accent、warn调色板
  )
));

// 应用主题到所有Material组件
@include mat.all-component-themes($cbh-light-theme);

2. 修改.sg-text-color的颜色引用

有两种常用方式:

方式一:直接从自定义调色板指定色调取色

替代旧的mat-color,使用mat.get-color-from-palette函数:

.sg-text-color {
  // 获取主调色板600色调的颜色
  color: mat.get-color-from-palette($mat-cbh-primary, 600);
  // 若需要对比色,添加第三个参数
  // color: mat.get-color-from-palette($mat-cbh-primary, 600, contrast);
}

方式二:从已定义的主题中取色

如果要跟随主题配置的默认色调,用mat.get-theme-color:

.sg-text-color {
  // 获取主题中primary角色的默认颜色
  color: mat.get-theme-color($cbh-light-theme, primary);
  // 也可指定色调,比如lighter/darker
  // color: mat.get-theme-color($cbh-light-theme, primary, lighter);
}

关键变化说明

  • 必须用@use '@angular/material' as mat;替代旧的@import,这是Sass模块系统的强制要求
  • mat.get-color-from-palette替代了旧的mat-color函数,用于从调色板提取指定色调
  • mat.get-theme-color可直接绑定主题配置的颜色,更贴合主题系统的设计逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 07:57:05