Search code examples
angularangular2-changedetection

Angular2: Watch an external variable outside of angular


I want to be able to watch and update when a variable outside of angular2 changes. So let's say I have this in an external javascript file:

var test = 1;

How can I bind this variable to a property in a component?

@Component({
   ...
})

export class MyComponent {
    watchy = window.test;
}

Apparently this should just work, according to this answer.
But it doesn't. If I change the variable in the console, the variable does not update displayed in a template. Am I missing something?


Solution

  • Angular only runs change detection when an async executed function completes. The function needs to be run inside Angulars zone for angular to recognize the async operation.

    Because your variable is changed from outside Angulars zone. Angular doesn't run change detection.

    You need to invoke change detection manually for Angular to recognize the changed variable. See also Triggering Angular2 change detection manually

    If you for example can dispatch an event instead of just setting a variable, you can listen to the event.

    window.dispatchEvent(new CustomEvent('test', {detail: 'newValue'}));
    
    @Component({
       ...
    })
    export class MyComponent {
        @HostListener('window:test', ['$event'])
        testListener(event) {
          this.watchy = event.detail;
        }
    }
    

    Invoked event handlers automatically invoke Angulars change detection, therefore there is nothing more to do.