Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggering change detection manually in Angular

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?

like image 594
jz87 Avatar asked Jan 16 '16 13:01

jz87


People also ask

What are the manual ways to trigger change detection in Angular?

We can trigger change detection manually by using detectChanges() , ApplicationRef. tick() , and markForCheck() that we mentioned earlier on AsyncPipe . detectChanges() on ChangeDetectorRef which will run change detection on this view and its children.

How does Angular detect change detection?

The answer is using observables. To run the change detector manually: Inject ChangeDetectorRef service in the component. Use markForCheck in the subscription method to instruct Angular to check the component the next time change detectors run. On the ngOnDestroy() life cycle hook, unsubscribe from the observable.

What is ChangeDetectorRef in Angular?

A change-detection tree collects all views that are to be checked for changes. Use the methods to add and remove views from the tree, initiate change-detection, and explicitly mark views as dirty, meaning that they have changed and need to be re-rendered.


1 Answers

Try one of these:

  • ApplicationRef.tick() - similar to AngularJS's $rootScope.$digest() -- i.e., check the full component tree
  • NgZone.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 children

You can inject ApplicationRef, NgZone, or ChangeDetectorRef into your component.

like image 134
Mark Rajcok Avatar answered Sep 26 '22 12:09

Mark Rajcok