Angular Material 5暗黑主题未应用到body的技术问题咨询
解决Angular Material 5暗黑主题无法应用到body的问题
看起来你已经走对了创建自定义主题的路子,但暗黑主题没作用到body上,我之前处理过类似的情况,给你几个针对性的解决步骤:
首先先确认你的SCSS代码是完整的,看你最后一行截断了,暗黑主题的混入应该补全:
@import '~@angular/material/theming'; @include mat-core(); $ip-primary: mat-palette($mat-indigo); $ip-accent: mat-palette($mat-pink, A200, A100, A400); $ip-theme: mat-light-theme($ip-primary, $ip-accent); $ip-theme-dark: mat-dark-theme($ip-primary, $ip-accent); .indigo-pink { @include angular-material-theme($ip-theme); } .indigo-pink-dark { @include angular-material-theme($ip-theme-dark); }
接下来解决body的应用问题:
1. 静态绑定暗黑主题
如果你的应用默认使用暗黑主题,直接在index.html的body标签上加上对应的类名就行:
<body class="indigo-pink-dark"> <app-root></app-root> </body>
2. 动态切换明暗主题
要是需要支持主题切换功能,你可以通过Angular的Renderer2来操作body的类:
在你的根组件里添加切换逻辑:
import { Component, Renderer2, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { constructor(private renderer: Renderer2) {} ngOnInit() { // 可以在这里默认设置主题,比如从本地存储读取 this.renderer.addClass(document.body, 'indigo-pink'); } toggleTheme() { const body = document.body; body.classList.toggle('indigo-pink'); body.classList.toggle('indigo-pink-dark'); } }
然后在模板里加个触发按钮:
<button (click)="toggleTheme()">切换明暗主题</button>
3. 确保body继承主题样式
有时候即使加了类,body的背景色还是没变化,这是因为Angular Material的主题不会自动给body设置样式,你可以在主题SCSS里补充:
.indigo-pink { @include angular-material-theme($ip-theme); body { background-color: mat-color($ip-theme.background, background); color: mat-color($ip-theme.foreground, text); } } .indigo-pink-dark { @include angular-material-theme($ip-theme-dark); body { background-color: mat-color($ip-theme-dark.background, background); color: mat-color($ip-theme-dark.foreground, text); } }
这样body就能正确继承主题的背景和文字颜色了。
内容的提问来源于stack exchange,提问作者danwellman
相关产品推荐
相关产品推荐

