How do I listen to changes to the class
attribute on the host element?
Asked
Active
Viewed 1,592 times
2 Answers
2
There's an easy way to do it, but that might not be appropriate in all situations.
Simply add 'class' as a @Prop and a @Watch:
@Prop() class: string;
@Watch('class') handleClassChange(class: string) {
console.log(class);
}

G. Tranter
- 16,766
- 1
- 48
- 68
0
Tracking DOM attribute changes requires the use of a MutationObserver
.
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
componentDidLoad() {
// Target element that will be observed
const target = this.el;
const config = {
attributes: true,
attributeOldValue: true,
attributeFilter: ['class']
};
function subscriberCallback(mutations) {
mutations.forEach((mutation) => {
console.log(mutation);
});
}
const observer = new MutationObserver(subscriberCallback);
observer.observe(target, config);
}

Suleman C
- 783
- 4
- 17
-
1An alternative would be to define your own property (e.g. `cssClass`) with a watcher, and then manually setting the `class` of the host element. – Thomas Apr 26 '19 at 16:44