Search code examples
angularangular2-changedetection

Change detection not working after using native JS


I have an Angular 2 app that builds a tree using mermaidJS, which is a JS (not TS) framework.

To bind clicks on this tree to Angular events, in my ngOnInit() method I create window functions, like this :

window['myFunctionToBeCalledFromTheTree'] = () => { ...}

It all works great.

The problem that occurs, is that once any of those functions is called, Angular doesn't detect changes anymore. I have found a quick workaround with the change detector, but I have to call it everytime.

My questoin is, is there a way to give back its automatic change detection to Angular ?


Solution

  • The problem is that the code in your callback runs outside Angular zone. You need to run it inside Angular zone:

    window['myFunctionToBeCalledFromTheTree'] = () => { this.zone.run(() => { ... } }
    

    You can't use change detector here because the changes made during change detection will not be picked by next change detection loop.