It's not recommended to change encapsulation frequently.
Instead of directly changing classes and styles in components, consider creating a state service that handles these changes.
A possible implementation could be like the following:
service
import { Injectable } from '@angular/core';
@Injectable()
export class StyleService {
private className: Subject<string> = new Subject<string>();
public className$: Observable<string> = this.className.asObservable();
set(className: string): any {
this.className.next(className);
}
}
To listen for changes:
...
private sub: Subscription;
...
this.sub = this.styleService.className$
.subscribe(class => {
// perform necessary actions
})
...
ngOnDestroy() {
// prevent memory leaks
this.sub.unsubscribe();
}
Simply call the set function when you want to change classes.
Make sure to declare the classes in the main styling file.
If you need an initial className value, you can use BehaviorSubject as shown below:
private class: BehaviorSubject<string> = new BehaviorSubject<string>('className');