2

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;
}
  • Can you make reproduction on stackblitz? I suspect some change detection issue. – Bojan Kogoj Jun 01 '21 at 14:09
  • No, this is the problem I don't know what triggers the it, to recreate an smaller example. The real app is big. But it is triggered without stop, and without doing any action on. Just having the app opened. I played with this example, I added one hostBinding on the app.component and I want to trigger it only when the 'isclicked' changes, but the function is called also when hover on the jokes. See the console.log. https://stackblitz.com/edit/angular-ivy-5wufmh?file=src/app/app.component.ts – Andrei Cristian Jun 01 '21 at 15:35
  • It's not exactly the same problem, but if I could understand this one maybe I can solve mine. Thanks! – Andrei Cristian Jun 01 '21 at 16:00
  • I can confirm change detection is not the problem. Beyond that I have no idea what is triggering HostBinding. – Bojan Kogoj Jun 01 '21 at 21:06
  • @AndreiCristian did you discover what was the issue? – superjos Mar 09 '22 at 18:36

1 Answers1

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