Angular Material 18迁移报错:调色板中不存在色调‘500’
问题解决:Angular 18+Material 18自定义M2调色板色调报错
问题根源
你遇到的报错是因为混用了Material Design 2(M2)和Material Design 3(M3)的颜色获取方法:
- 你用
mat.m2-define-palette创建了M2风格的调色板(色调为50/100...900/A系列) - 但后续用了M3的
mat.get-theme-color函数获取颜色,该函数仅支持M3的色调体系(0/10/20...100等) - 代码中还存在未定义的
$accent-palette变量,这也是报错的诱因之一
修复步骤
- 补全未定义变量:从主题配置中获取accent调色板
- 替换颜色获取函数:用M2专属的
mat.get-color-from-palette替代M3的mat.get-theme-color
修改后的完整代码
@use 'sass:map'; @use '@angular/material' as mat; $md-primary: ( 50 : #fee6fe, 100 : #fcbffd, 200 : #fa95fb, 300 : #f76bf9, 400 : #f64bf8, 500 : #f42bf7, 600 : #f326f6, 700 : #f120f5, 800 : #ef1af3, 900 : #ec10f1, A100 : #ffffff, A200 : #feebff, A400 : #fdb8ff, A700 : #fc9eff, contrast: ( 50 : #000000, 100 : #000000, 200 : #000000, 300 : #000000, 400 : #000000, 500 : #ffffff, 600 : #ffffff, 700 : #ffffff, 800 : #ffffff, 900 : #ffffff, A100 : #000000, A200 : #000000, A400 : #000000, A700 : #000000, ) ); $md-secondary: ( 50 : #f6e1ff, 100 : #eab3ff, 200 : #dc80ff, 300 : #cd4dff, 400 : #c327ff, 500 : #b801ff, 600 : #b101ff, 700 : #a801ff, 800 : #a001ff, 900 : #9100ff, A100 : #ffffff, A200 : #f9f2ff, A400 : #e0bfff, A700 : #d4a6ff, contrast: ( 50 : #000000, 100 : #000000, 200 : #000000, 300 : #000000, 400 : #ffffff, 500 : #ffffff, 600 : #ffffff, 700 : #ffffff, 800 : #ffffff, 900 : #ffffff, A100 : #000000, A200 : #000000, A400 : #000000, A700 : #000000, ) ); //GLOBAL $my-primary: mat.m2-define-palette($md-primary, 500); $my-secondary: mat.m2-define-palette($md-secondary, 500); $my-theme: mat.m2-define-light-theme(( color: ( primary: $my-primary, accent: $my-secondary, ) )); @include mat.all-component-themes($my-theme); $color-config: mat.get-color-config($my-theme); $primary-palette: map.get($color-config, 'primary'); // 补全accent调色板变量定义 $accent-palette: map.get($color-config, 'accent'); // 替换为M2的颜色获取函数 $primary: mat.get-color-from-palette($primary-palette, 500); $secondary: mat.get-color-from-palette($accent-palette, 500); $light-secondary: mat.get-color-from-palette($accent-palette, 300); $light-primary: mat.get-color-from-palette($primary-palette, 300); //PALETTE BASICS $light-grey: rgb(228, 228, 228); $grey: #252525; $secondary-text: #525252; $black: rgb(20, 20, 20); :root { --primary: #{$primary}; --secondary: #{$secondary}; --light-secondary: #{$light-secondary}; --light-primary: #{$light-primary}; --light-grey: #{$light-grey}; --grey: #{$grey}; --secondary-text: #{$secondary-text}; --black: #{$black}; }
额外说明
如果后续计划迁移到M3调色板体系,可以直接使用M3的mat.define-palette函数,色调遵循0/10/20...100的规则,同时配套使用mat.get-theme-color获取颜色。
内容的提问来源于stack exchange,提问作者sivir
相关产品推荐
相关产品推荐

