角度-可以使用单击功能来更改另一个组件中元素的样式吗



我在组件中有这个按钮,当有人点击它时,它会改变我应用程序中许多元素的样式。我面临的问题是,我的函数只适用于点击函数所在组件内的css类

HTML

<a role="button" (click)="toggleChange()">button</a>
<div [ngClass]="[divStyle]">test</div>

scs-

.div-default {
background-color: #AAA;
}
.div-changed {
background-color: #BBB;  
}

TS

divStyle = 'div-default';
toggleChange(): void {
if (this.divStyle == 'div-changed') {
this.divStyle = 'div-default';
} else {
this.divStyle = 'div-changed';
}
}

我可以使用这个相同的函数来更改应用程序中另一个组件中元素的样式吗?如果没有,创建一个按钮的最佳方式是什么?当单击该按钮时,它会改变我应用程序中不同组件中的许多样式?

如果您试图实现一个;切换暗/亮模式";按钮,然后我建议看看如何使用css实现主题。

如果没有,那么既然你试图更改应用程序中任意组件的类别,我建议你:

  • 使用像redux这样的状态管理库,并在store中的states处设置这些classes
  • 实现一个跟踪所有这些类的服务:
class StylingService {
divStyle = 'div-default';
toggleChange(): void {
if (this.divStyle == 'div-changed') {
this.divStyle = 'div-default';
} else {
this.divStyle = 'div-changed';
}
}
... and then in the component that need to use the class:
class SomeComponent {
divStyle: string;
constructor(private stylingService StylingService) {
this.divStyle = stylingService.divStyle;
}
}
... the button would look like:
<button (click)="stylingService.toggleChange()">Change class</button>

角度方式:https://angular.io/api/core/Renderer2

import { Inject, Renderer2 } from '@angular/core';
import { DOCUMENT } from '@angular/common';
constructor(
@Inject(DOCUMENT) private document: Document, 
private renderer: Renderer2,
) {
}
toggleChange(): void {
const element = this.document.body; // for example
const className = 'example'; // for example
if (element.classList.contains(className)) {
this.renderer.removeClass(element, className);
} else {
this.renderer.addClass(element, className);
}
}

最新更新