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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With