角度 2+ 添加或删除属于另一个组件的元素的类



我正在一个有 4 个组件的应用程序上使用 Angular 2 ...app.component and other.component

app.component上.html我有一个div,里面有一个名为myClass的类...

<div class="myClass"></div>

other.component.ts我目前有:

ngOnInit() {
 jQuery('.myClass').removeClass();
 jQuery('.myClass').addClass('someClassName');
}

我想以角度的方式做到这一点,而不是使用jQuery。

我的问题是...我如何使用 Angular 2+ 做同样的事情?

如果OtherComponentAppComponent以外的另一条路线上,那么您可以使用服务来执行此操作:

app.component.html

<div class="myClass" #concernedDiv></div>

app.component.ts

@ViewChild('concernedDiv') concernedDiv: ElementRef;
constructor(private myService; MyService) {}
ngOnInit() {
  this.myService.onOtherInit.subscribe(event => {
    this.concernedDiv.className = this.concernedDiv.replace('myClass', '').trim();
  });
}

my-service.service.ts

private sub: Subject<any> = new Subject();
public onOtherInit: Observable<any> = this.sub.asObservable();
emitEvent() { this.sub.next(/* anything you want */); }

other.component.ts

constructor(private myService: MyService) {}
ngOnInit() { this.myService.emitEvent(); }

通过使用ngClass,您可以使用语句来添加/删除类

在组件中:

yourBooleanValue: boolean;
ngOnInit() {
    this.yourBooleanValue = true;
}

在 html 中:

<div [ngClass]="{ 'someClassName': yourBooleanValue }"></div>