I'm writing an Angular component that has a property Mode(): string.
I would like to be able to set this property programmatically not in response to any event.
The problem is that in the absence of a browser event, a template binding {{Mode}} doesn't update.
Is there a way to trigger this change detection manually?
Try one of these:
ApplicationRef.tick() - similar to AngularJS's $rootScope.$digest() -- i.e., check the full component treeNgZone.run(callback) - similar to $rootScope.$apply(callback) -- i.e., evaluate the callback function inside the Angular zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.ChangeDetectorRef.detectChanges() - similar to $scope.$digest() -- i.e., check only this component and its childrenYou can inject ApplicationRef, NgZone, or ChangeDetectorRef into your component.
I used accepted answer reference and would like to put an example, since Angular 2 documentation is very very hard to read, I hope this is easier:
Import NgZone:
import { Component, NgZone } from '@angular/core';
Add it to your class constructor
constructor(public zone: NgZone, ...args){}
Run code with zone.run:
this.zone.run(() => this.donations = donations)
I was able to update it with markForCheck()
Import ChangeDetectorRef
import { ChangeDetectorRef } from '@angular/core';
Inject and instantiate it
constructor(private ref: ChangeDetectorRef) {
}
Finally mark change detection to take place
this.ref.markForCheck();
Here's an example where markForCheck() works and detectChanges() don't.
https://plnkr.co/edit/RfJwHqEVJcMU9ku9XNE7?p=preview
EDIT: This example doesn't portray the problem anymore :( I believe it might be running a newer Angular version where it's fixed.
(Press STOP/RUN to run it again)