Why @HostBinding is triggered continuously even though the variable didn't changed? (Angular)

429 views Asked by At

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;
}
1

There are 1 answers

0
Praveen B N On

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();
   }