1

I have a function on the window object that changes data in my angular4 app, however the view does not update until I click into one of the inputs within the angular app. Is there a way I can make it update immediately?

I believe this is related to Angular zones, is that correct?

Code:

In the below code vm is referencing my Angular component.

        window.callback = function(data) {
            vm.setKey(data.result);
        }

The below function is in the Angular component, and is correctly setting the data correctly, but it is not updated in the view until the app is interacted with again.

setKey(result) {
    this.key = result;
}
Michael
  • 1,087
  • 1
  • 9
  • 12
  • This has to do with the fact that the function is running outside the NgZone, yes. If the model is mutated outside of Angular's zone, it doesn't know anything has changed. Would be easier to help if some of your code were provided in the question. – LarsMonty Jul 26 '17 at 23:28
  • @LarsMontanaro done – Michael Jul 26 '17 at 23:46

1 Answers1

3

If you'd like to manually fire an Angular change detection loop in a function, you can inject a reference to ChangeDetectorRef into your components, and call the detectChanges() method to fire this.

Will look something like this:

// import ChangeDetectorRef
import { ChangeDetectorRef } from '@angular/core'

// Your component's constructor
constructor(changeDetector : ChangeDetectorRef)
{ ... }

// Your setKey method
setKey(result) {
    this.key = result;
    this.changeDetector.detectChanges();
}

You can read more about how change detection works in Angular here: https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html

LarsMonty
  • 727
  • 8
  • 20