Reputation: 783
How do I listen to changes to the class
attribute on the host element?
Upvotes: 2
Views: 1978
Reputation: 17928
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);
}
Upvotes: 2
Reputation: 783
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);
}
Upvotes: 0