[英]Angular 2+ Add or Remove a Class of an element that belongs to another component
I am using Angular 4 on an application where I have 2 components ... app.component and other.component 我在一个应用程序上使用Angular 4,我有2个组件... app.component和other.component
On app.component.html I have a div with a class called myClass ... 在app.component.html上我有一个名为myClass的类的div ...
<div class="myClass"></div>
On other.component.ts
I currently have: 在
other.component.ts
我目前有:
ngOnInit() {
jQuery('.myClass').removeClass();
jQuery('.myClass').addClass('someClassName');
}
I want to do this the angular way instead of using jQuery. 我想以角度方式而不是使用jQuery。
My question is...How do I do this same thing with Angular 2+ ? 我的问题是......我如何使用Angular 2+做同样的事情?
If OtherComponent
is on another route than AppComponent
, then you could use a service to do that : 如果
OtherComponent
是比另一种途径AppComponent
,那么你可以使用一个服务做到这一点:
app.component.html app.component.html
<div class="myClass" #concernedDiv></div>
app.component.ts 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 我-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 other.component.ts
constructor(private myService: MyService) {}
ngOnInit() { this.myService.emitEvent(); }
By using ngClass
you can use statements to add / remove a class 通过使用
ngClass
您可以使用语句来添加/删除类
In your component: 在您的组件中:
yourBooleanValue: boolean;
ngOnInit() {
this.yourBooleanValue = true;
}
In html: 在html中:
<div [ngClass]="{ 'someClassName': yourBooleanValue }"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.