3

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 ?

11
  • 2
    try injecting NgZonein constructor(zone: NgZone) and wrapping your functions with window['myFunctionToBeCalledFromTheTree'] = () => { this.zone.run(() => { ... } } Commented May 23, 2017 at 10:18
  • @Maximus I don't know if this is necessary - NgZone.run is meant to be run inside NgZone.runOutsideAngular - I think most code will automatically be run inside a zone, even raw JS code. Commented May 23, 2017 at 10:58
  • @DanielCooke Then what would you do ? Commented May 23, 2017 at 12:43
  • Inject ChangeDetectorRef and call changeRef.detectChanges manually. stackoverflow.com/questions/34827334/… -- if that doesn't work call .markForCheck() Commented May 23, 2017 at 12:45
  • @DanielCooke I already did that, the problem is that you have to call it at every method call or every variable change. I would like to have the automatic detection, like it is when you don't exit the Angular context. Commented May 23, 2017 at 12:57

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments