单击开关时如何在Angular中切换深色主题? [英] How to toggle dark theme in Angular when I click on the switch?

查看:99
本文介绍了单击开关时如何在Angular中切换深色主题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用角度显示,并且尝试在浅色和深色主题之间切换.拨动开关在我的标题组件中.请看下面

I am using angular and I am trying to switch between light and dark themes. The toggle switch is in my header component. Please see below

我的标头组件是应用程序组件中的子组件.另请参见

And my header component is the child component in the app component. See below also

// app.component.html    

    <app-header (mode)="receiveMode($event)"></app-header>

     <router-outlet></router-outlet>

因此,我在标题组件TS文件中为切换主题设置了布尔值

Therefore, I set the boolean value for the toggle theme in my header component TS file

// 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.component.ts文件中,以便所有其他组件也可以具有主题(不仅仅是HomeComponent).

I then pass that value to the parent component with the Output decorator and receive it in the app.component.ts file so that all other components can have the theme as well, (not just HomeComponent).

// 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';
}

然后我从app.component.html文件中的app-header接收布尔值

I then receive the boolean value from the app-header in the app.component.html file

// app.component.html

    <app-header (mode)="receiveMode($event)"></app-header>

    <router-outlet></router-outlet>

然后我在styles.css中将darkTheme类添加到了我的全局样式表中

And I added the darkTheme class to my global stylessheet in styles.css

.darkTheme {
    background-color: black;
}

我想知道如何使用ngClass或ngStyle根据布尔值有条件地设置它.

I want to know how can use ngClass or ngStyle to set it conditionally based on the boolean value.

推荐答案

这里是一种方法:

<div [ngClass]="{
  darkTheme: setMode
}">
</div>

您还可以在同一ngClass中添加其他类和条件.

You can also add additional classes and conditions in the same ngClass.

另一个:

<div [class.darkTheme]="setMode"></div>

如我的评论中所述,我更喜欢这种方法:

As mentioned in my comment, I would prefer this approach:

<link rel="stylesheet" href="/theme/css/dark-theme.min.css" *ngIf="setMode">

这篇关于单击开关时如何在Angular中切换深色主题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆