Aside from the traditional method of accessing the value of the class attribute, it seems that the issue at hand is related to asynchronous behavior based on your remarks.
Instead of resorting to a makeshift setTimeout
fix, my suggestion would be to implement a mutation observer and respond to attribute changes accordingly.
Here's a sample approach to tackle this.
PS: I have adjusted the response to better align with your goals. Ultimately, this adjustment may not have a significant impact, except in cases where the banner state changes before the debounce period elapses, resulting in immediate emission and potential time savings compared to using setTimeout
.
bannerIsActive$ = new BehaviorSubject<boolean>(false);
ngAfterViewInit() {
const banner = document.getElementById('banner');
const observer = new MutationObserver((mutations: MutationRecord[]) => {
const mutation = mutations[0];
const classList: DOMTokenList = mutation.target['classList'];
this.bannerIsActive$.next(mutation.attributeName === 'class' && classList.contains('active'));
});
observer.observe(banner, {
attributes: true
});
this.bannerIsActive$.pipe(
debounce(isActive => timer(isActive ? 0 : 1000)),
take(1)
).subscribe(isActive => {
// perform actions based on the banner state
});
}