如何使用 Angular(不是 Material)制作切换深色主题

How to make a toggle dark theme using Angular ( Not Material )

我想为我的项目制作一个可在每个组件中使用的切换深色主题

我找到的资源在 angular material 上。但我不想用那个,

有什么办法吗?

请帮忙!

为此,在您的切换按钮上添加点击功能并更改属性并相应地更改颜色。像这样:

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

所以这里发生的事情是,最初由于布尔值是暗的,div 将有一个 'white-class' 背景,因为我在 [[=20= 上添加了 '!isDark' 条件]-class] 当你点击按钮时,我将 'isDark' 更改为 '!isDark' 这意味着 'isDark' 现在将变为 true 然后背景变为深色.

这是您可以遵循的一种方法。

关于你的另一个问题:如何在全球范围内做到这一点?你可以这样做:

// 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>