当用户切换位于标题组件中的开关时,我试图切换暗模式。参见下图:
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-item nav-link active" href="/">Home <span class="sr-only">(current)</span></a>
<a class="nav-item nav-link" href="/about">About</a>
<a class="nav-item nav-link" href="/contact">Contact</a>
<a class="nav-item nav-link" href="/resume">Resume</a>
</div>
</div>
<div class="custom-control custom-switch">
<input (change)="onChangeToggle()" type="checkbox" class="custom-control-input" id="toggleTheme">
<label class="custom-control-label" for="toggleTheme">Dark Mode</label>
</div>
</nav>
我的标头组件ts文件包含一个名为setDark的布尔值,该布尔值在事件发射器中通过Output装饰器触发:
// header.component.ts
import { Component, OnInit , Output, EventEmitter} from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
@Output() mode = new EventEmitter<boolean>();
setDark = false;
constructor() { }
ngOnInit(): void {
}
onChangeToggle() {
this.setDark = !this.setDark;
this.mode.emit(this.setDark);
console.log(this.setDark);
}
}
然后在app.comoonent.html中接收布尔值
<app-header (mode)="receiveMode($event)"></app-header>
<router-outlet></router-outlet>
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
setMode = false;
receiveMode($event) {
this.setMode = $event;
console.log("MODEEEE", this.setMode);
}
title = 'about-me';
}
我试图像这样将div包裹在app-header和router-out周围:
<app-header (mode)="receiveMode($event)"></app-header>
<div class="darkTheme">
<router-outlet></router-outlet>
并使用ngClass:
<div [ngClass]="{
darkTheme: setMode
}">
</div>
但是它不起作用。我确实检查了切换开关时布尔值是否已登录到控制台。是的。
答案 0 :(得分:2)
看看这个堆叠闪电战:https://stackblitz.com/edit/angular-rubaka?file=src/app/toolbar-multirow-example.html
它在#container:ElementRef:
上切换类“黑暗主题” <div #container style="padding: 4rem;" class="mat-typography dark-theme">
styles.scss在第28行(默认主题)定义了两个不同的主题...
// Include the default theme styles.
@include angular-material-theme($candy-app-theme);
并在第39行(深色主题)...
.dark-theme {
@include angular-material-theme($dark-theme)
};
希望这会有所帮助。