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

Angular 14迁移至16后Material主题对比色不生效问题

解决Angular 16升级后Material自定义对比色不生效的问题

问题出在你调用mat.define-palette时的参数错误。Angular Material 15+版本对define-palette函数新增了对比色相关参数,你当前代码多传的最后一个800会触发自动对比色计算逻辑,直接覆盖了自定义调色板中配置的白色对比色。

修正步骤

移除mat.define-palette调用中多余的第五个参数,让函数使用你自定义调色板里预定义的对比色配置。

修改后的完整代码:

@use '@angular/material' as mat;
@include mat.core();

$my-palette: (
  50: #fff7e0,
  100: #ffeab1,
  200: #ffdc7e,
  300: #ffd04a,
  400: #ffc41f,
  500: #ffba00,
  600: #ffac00,
  700: #ff9900,
  800: #ff8700,
  900: #ee6001,
  contrast: (
    50: mat.get-color-from-palette(mat.$indigo-palette, '50-contrast'),
    100: mat.get-color-from-palette(mat.$indigo-palette, '100-contrast'),
    200: mat.get-color-from-palette(mat.$indigo-palette, '200-contrast'),
    300: mat.get-color-from-palette(mat.$indigo-palette, '300-contrast'),
    400: mat.get-color-from-palette(mat.$indigo-palette, '400-contrast'),
    500: #ffffff,
    600: #ffffff,
    700: #ffffff,
    800: #ffffff,
    900: #ffffff
  )
);

// 移除最后一个多余的800参数
$my-primary: mat.define-palette($my-palette, 800, 500, 800);
$my-accent:  mat.define-palette($my-palette, 800, 500, 800);

$my-theme: mat.define-light-theme((
  color: (
    primary: $my-primary,
    accent: $my-accent
  ),
  density: 0
));
@include mat.all-component-themes($my-theme);

补充说明

如果需要显式声明对比色逻辑,可以在define-palette中添加auto作为第五个参数(默认值即为auto,可省略),明确指定使用调色板内预定义的对比色:

$my-primary: mat.define-palette($my-palette, 800, 500, 800, auto);

修改后,自定义的白色对比色会正常生效,替代自动计算的黑色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 16:33:32