Search code examples
angularzones

updating angular view from outside


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

Solution

  • 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