返回
Angular Material 主题系统(三)--多主题切换
前端
2024-01-14 00:26:03
引言
在上一篇文章中,我们介绍了如何自定义 Material 主题。现在,我们来看看如何定义多个主题,并在运行时动态切换。我们可以采用官网介绍的类名包裹方式,或者我们也可以预先编译,按需引入。话不多说,let's rock the code!😎
切换暗黑主题
正如上篇所言,我们首先就来实现怎么切换网站的暗黑主题。注意,我们这里需要用到的主题变量:
body {
color: $dark-primary-text;
background: $dark-background;
}
.dark-theme .mat-toolbar {
background: $dark-primary;
}
然后,我们可以在组件中通过如下方式切换主题:
import { Component } from '@angular/core';
@Component({
selector: 'app-theme-switcher',
templateUrl: './theme-switcher.component.html',
styleUrls: ['./theme-switcher.component.scss']
})
export class ThemeSwitcherComponent {
isDarkTheme = false;
toggleTheme() {
this.isDarkTheme = !this.isDarkTheme;
document.body.classList.toggle('dark-theme');
}
}
在组件的 HTML 中,我们就可以使用如下按钮来切换主题:
<button (click)="toggleTheme()">切换主题</button>
预编译多主题
除了上面介绍的类名包裹方式外,我们还可以通过预编译的方式来实现多主题切换。这种方式的好处是,我们可以将不同的主题打包成单独的 CSS 文件,然后在运行时按需引入。这样可以减少主 CSS 文件的大小,并提高页面的加载速度。
具体做法是,我们在 angular.json
文件中添加如下配置:
"styles": [
"src/styles.scss",
"src/dark-theme.scss"
]
然后,我们在 src/dark-theme.scss
文件中定义暗黑主题的样式:
body {
color: #fff;
background: #000;
}
.dark-theme .mat-toolbar {
background: #333;
}
最后,我们在组件中通过如下方式切换主题:
import { Component } from '@angular/core';
@Component({
selector: 'app-theme-switcher',
templateUrl: './theme-switcher.component.html',
styleUrls: ['./theme-switcher.component.scss']
})
export class ThemeSwitcherComponent {
isDarkTheme = false;
toggleTheme() {
this.isDarkTheme = !this.isDarkTheme;
if (this.isDarkTheme) {
document.head.appendChild(document.createElement('link')).href = 'dark-theme.css';
} else {
document.head.removeChild(document.head.lastChild);
}
}
}
总结
以上就是 Angular Material 多主题切换的两种实现方式。第一种方式比较简单,但是需要在运行时动态修改 DOM。第二种方式稍微复杂一些,但是可以减少主 CSS 文件的大小,并提高页面的加载速度。
希望本文对您有所帮助!