【问题标题】:How to make a toggle dark theme using Angular ( Not Material )如何使用 Angular(非材质)制作切换深色主题
【发布时间】:2021-07-20 03:30:53
【问题描述】:

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

我找到的资源是关于角材料的。但我不想用那个,

有什么办法吗?

请帮忙!

【问题讨论】:

  • Angular 中没有内置主题。您需要构建它。
  • 嘿@HereticMonkey 我该如何构建它?
  • @HereticMonkey 不,你误会我的意思了。我的意思是,你能告诉我我该怎么做的步骤/技术吗?

标签: javascript angular typescript dependency-injection rxjs


【解决方案1】:

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

// 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 将有一个“白色类”背景,因为我在 [class.white-class] 上添加了一个“!isDark”条件,当你点击按钮,我将“isDark”更改为“!isDark”,这意味着“isDark”现在将变为真,然后背景变为深色。

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

【讨论】:

  • 非常感谢兄弟!!!!!!!但我有一个问题!当我在 .ts 文件中使用 private 时。它抛出一个错误。问题是这如何适用于每个组件的全局?
  • 你不需要使用private...你可以简单地定义isDark: boolean = false;
【解决方案2】:

对于您的另一个问题:如何在全球范围内执行此操作?你可以这样做:

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


【讨论】:

    猜你喜欢
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 2019-11-19
    • 2021-05-03
    相关资源
    最近更新 更多