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

Angular Material 18中mat.define-palette()报“Undefined function”错误及适配

适配Angular Material 18的styles.scss修改方案

Angular Material 18彻底移除了旧版Sass主题API(包括mat.define-palette、mat.define-light-theme等函数),改用CSS变量驱动的新主题系统,这是导致编译错误的核心原因。以下是修改后的完整代码及关键说明:

修改后的styles.scss代码

@use '@angular/material' as mat;

// 初始化Angular Material基础样式
@include mat.core();

// 定义浅色主题,配置主色调、强调色、警告色及对应色调等级
@include mat.theme((
  color: (
    theme-type: light,
    primary: mat.$indigo-palette,
    accent: mat.$indigo-palette,
    warn: mat.$red-palette,
    // 对应旧版define-palette的三个参数:默认色、浅色、深色
    primary-scale: (
      default: A400,
      lighter: A100,
      darker: A700
    )
  )
));

// 为所有Material组件应用主题
@include mat.all-component-themes();

关键变化说明

  • 移除旧版mat.define-palette调用:直接传入预设调色板(如mat.$indigo-palette)到主题配置中
  • 替换mat.define-light-theme:在mat.theme()配置项里设置theme-type: light即可定义浅色主题
  • 自定义色调等级:通过primary-scale/accent-scale/warn-scale配置块,指定默认、更浅、更深的色调键(对应旧版define-palette的第二、三、四参数)
  • 简化组件主题应用:调用mat.all-component-themes()时无需传入主题对象,它会自动使用之前通过mat.theme()定义的主题

自定义调色板示例(可选)

如果需要使用自定义调色板,可按如下方式定义:

@use '@angular/material' as mat;

@include mat.core();

// 自定义主色调调色板
$custom-primary-palette: (
  50: #e8f5e9,
  100: #c8e6c9,
  200: #a5d6a7,
  300: #81c784,
  400: #66bb6a,
  500: #4caf50,
  600: #43a047,
  700: #388e3c,
  800: #2e7d32,
  900: #1b5e20,
  A100: #b9f6ca,
  A200: #69f0ae,
  A400: #00e676,
  A700: #00c853
);

@include mat.theme((
  color: (
    theme-type: light,
    primary: $custom-primary-palette,
    primary-scale: (
      default: A400,
      lighter: A100,
      darker: A700
    ),
    accent: mat.$pink-palette,
    warn: mat.$red-palette
  )
));

@include mat.all-component-themes();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 13:53:28