Reputation:
I am using Angular 4 on an application where I have 2 components ... app.component and other.component
On app.component.html I have a div with a class called myClass ...
<div class="myClass"></div>
On other.component.ts
I currently have:
ngOnInit() {
jQuery('.myClass').removeClass();
jQuery('.myClass').addClass('someClassName');
}
I want to do this the angular way instead of using jQuery.
My question is...How do I do this same thing with Angular 2+ ?
Upvotes: 1
Views: 1804
Reputation:
If OtherComponent
is on another route than AppComponent
, then you could use a service to do that :
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(); }
Upvotes: 1
Reputation: 1239
By using ngClass
you can use statements to add / remove a class
In your component:
yourBooleanValue: boolean;
ngOnInit() {
this.yourBooleanValue = true;
}
In html:
<div [ngClass]="{ 'someClassName': yourBooleanValue }"></div>
Upvotes: 0