Search code examples
angularionic-frameworkdata-bindingdom-events

Angular 4 Two-Way Data Binding breaks with EventListener


I have the problem, that my data bindings break if I push the Ionic Page by an event listener event.

ionViewDidLoad() {
document.addEventListener('admob.rewardvideo.events.REWARD', () => {
  this.goToScriptedGame();
});

The user has to watch the ad video, before he can access the page.

Sadly all two-way bindings like {{title}} don't change anymore, they only show the init value.

I discovered, that if a press the "devices" back button (which is disabled at a certain point) the values are shown correctly.

The variables themselves are all correct and everything is working fine but it's just the broken binding.


Solution

  • You need to trigger change detection manually, when you want to bind to events via document.addEventListener, otherwise angular does not know about it.

    You are probably looking for ApplicationRef#tick(), that will trigger full component tree change detection.

    import { ApplicationRef } from '@angular/core';
    
    constructor(private appRef: ApplicationRef) {}
    
    ionViewDidLoad() {
      document.addEventListener('admob.rewardvideo.events.REWARD', () => {
        this.goToScriptedGame();
        this.appRef.tick();
      });
    }
    

    See this question for more information and other possibilities: Triggering Angular2 change detection manually