Suleman C
Suleman C

Reputation: 783

Stencil.js - Listen to class attribute changes on host element

How do I listen to changes to the class attribute on the host element?

Upvotes: 2

Views: 1978

Answers (2)

G. Tranter
G. Tranter

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

Suleman C
Suleman C

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

Related Questions