'Why @HostBinding is triggered continuously even though the variable didn't changed? (Angular)
I joined a new Angular project and on the app.component.ts are some @HostBindings that are called non-stop even though there is no direct event that is triggered. Ex.:
settings = {
layout: { isCollapsed: false }
}
@HostBinding('class.aside-collapsed') get isCollapsed() {
return this.settings.layout.isCollapsed;
};
The layout object is part of SettingsService and the property is only changed when the side-menu is toggled: header.component.ts:
toggleMobileMenu(event: any) {
event.preventDefault();
this.settings.layout.isCollapsed = !this.settings.layout.isCollapsed;
}
Solution 1:[1]
A non-angular hack using mutation observer,
const targetNode = document.querySelector('element_on_which_class_exists');
const config = { attributes: true, childList: false, characterData: false };
const callBack = (mutations) => {
mutations.forEach(({ type, attributeName, target: { classList } }) => {
if (type === 'attributes' && attributeName === 'class') {
// Do something here ...
}
});
}
const isCollapsedMutationObserver = new MutationObserver(callBack);
isCollapsedMutationObserver.observe(targetNode, config);
ngOnDestory() {
isCollapsedMutationObserver.disconnect();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Praveen B N |