我在有 2 个组件的应用程序上使用 Angular 4 ... app.component 和 other.component
在app.component.html 上,我有一个名为myClass的类的 div ...
<div class="myClass"></div>
在other.component.ts
我目前有:
ngOnInit() {
jQuery('.myClass').removeClass();
jQuery('.myClass').addClass('someClassName');
}
我想以角度方式而不是使用 jQuery 来执行此操作。
我的问题是......我如何用 Angular 2+ 做同样的事情?
如果OtherComponent
在另一条路线上AppComponent
,那么您可以使用服务来做到这一点:
应用程序组件.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();
});
}
我的服务.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(); }
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句