我正在一个有 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+ 做同样的事情?
如果OtherComponent
在AppComponent
以外的另一条路线上,那么您可以使用服务来执行此操作:
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>