[英]How to make a toggle dark theme using Angular ( Not Material )
我想為我的項目制作一個切換深色主題,該主題適用於每個組件
我找到的資源在 angular 材料上。 但我不想用那個,
有什么辦法嗎?
請幫忙!
為此,在您的切換按鈕上添加點擊功能並更改屬性,並相應地更改 colors。 像這樣的東西:
// In your HTML
<div [class.dark-class]="isDark" [class.white-class]="!isDark">
<button (click)="isDark = !isDark">Toggle background</button>
</div>
// In your SCSS file, have 2 class, one called dark-class and the other white-class
.dark-class { background: black }
.white-class { backgrond: white }
// In your component.ts file, add a boolean value 'isDark' and set it to false initially
private isDark: boolean = false;
所以這里發生的事情是,最初由於 boolean 值是暗的,div 將有一個“白色類”背景,因為我在 [class,white-class] 上添加了一個“.isDark”條件,當你點擊按鈕時,我正在將“isDark”更改為“.isDark”,這意味着“isDark”現在將變為真,然后背景變為深色。
這是您可以遵循的一種方法。
對於您的另一個問題:如何在全球范圍內做到這一點? 你可以這樣做:
// If you have a service which is being used across all the components, you can use it otherwise create a new one like this:
1) Create a file and name it a commonService
// Inside common service:
@Injectable({ provideIn: 'root' })
export class CommonService {
globalIsDark: boolean = false;
setGlobalDark(value: boolean) {
this.globalIsDark = value;
}
getGlobalDark(): boolean {
return this.globalIsDark;
}
}
// Now in your styles.scss file, add the dark and white classes
.dark-class { background: black }
.white-class { backgrond: white }
// In every component, wherever you want to use, do this:
constructor(private commonService: CommonService) {}
isComponentBGDark: boolean;
ngOnInit() {
// If you want to use what's there, do this
this.isComponentBGDark = this.commonService.getGlobalDark();
// If you want to set the theme to dark, do this:
this.commonService.setGlobalDark(true);
}
// In your component HTML
<div [class.dark-class]="isComponentBGDark"
[class.white-class]="!isComponentBGDark"
>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.