Design sketch:
Framework version:
The first scheme is to use SCSS preprocessor. The idea is to control the value of custom attributes on body by clicking on events, and to switch CSS styles by using scss@mixin instructions. The specific code is implemented as follows
-
Create new base.scss (topic parameter variable) and mixin.scss style files under assests folder
base.scss:$background-color-blue: #1dd3f3; $background-color-black: #0c0b0b;
mixin.scss:
@import './base.scss'; @mixin bg_color() { :host-context([data-theme='blue']) & { background-color: $background-color-blue; } :host-context([data-theme='black']) & { background-color: $background-color-black; } }
-
Global styles.scss style file introduces mixin.scss file
@import './assets/scss/mixin.scss';
-
Apply the style defined in mixin.scss file in app.component.scss
@import '../styles.scss'; .toolbar_scss{ @include bg_color }
-
Modify the app.component.html file (MatIconModule is introduced into app.module.ts, MatMenuModule can be used after the MatIconModule library needs to be installed with mat-menu tag and the ng add@angular/material command is executed)
<div class="spacer"> <button mat-icon-button [matMenuTriggerFor]="menu" aria-label="Example icon-button with a menu"> <mat-icon>more_vert</mat-icon> </button> <mat-menu #menu="matMenu" style="margin-top: 68px"> <button mat-menu-item (click)="changeTheme('blue')"> <mat-icon>dialpad</mat-icon> <span>blue</span> </button> <button mat-menu-item (click)="changeTheme('black')"> <mat-icon>voicemail</mat-icon> <span>black</span> </button> </mat-menu> </div>
-
The app.component.ts file controls the value of the custom attribute on the body by clicking on the event and stores it in the local Storage.
export class AppComponent { title = 'angular-ui'; themeUI: string; ngOnInit() { this.setTheme(); } changeTheme(theme: string) { const body = document.getElementsByTagName('body')[0]; const currentTheme = body.getAttribute(`data-theme`); if (currentTheme !== theme) { body.setAttribute('data-theme', theme); this.saveTheme(theme) } } saveTheme(theme: string) { localStorage.setItem(`theme`, theme); } setTheme() { this.themeUI = localStorage.getItem('theme') || 'blue' const body = document.getElementsByTagName('body')[0]; body.setAttribute('data-theme', this.themeUI); } }
Summary: @mixin bg_color() takes advantage of the host-context() pseudo-Class selector. It's similar: it's used in the form of host(). It finds the CSS class in the ancestor node of the current component host element until the root node of the document.
Reference resources: https://segmentfault.com/a/11...