Friday, April 14, 2017

Refresh the UI manually if Angular2 doesn't detect changes in component variables

Sometimes Angular is unable to detect or mark changes so even if you change a variable, UI remains untouched. In this case, if any other solution doesn't work there is a simple workaround based on `ChangeDetectorRef` class. Simply inject it into your component and call markForCheck() and detectChanges():



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
  constructor(ref: ChangeDetectorRef) {
  }

  ngAfterViewInit(): void {
      // no matter of how and where you need a refresh, 
      // simply call markForCheck & detectChanges anywhere you want
      // In my code, I have called them in a custom event handler
      this.myService.somethingChanged$.subscribe(e => {
          this.ref.markForCheck();
          this.ref.detectChanges();
      });
  }

No comments:

Post a Comment