Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger Angular change detection from console

Tags:

angular

In AngularJS we were able to trigger a digest cycle by getting the ng-app element with something like

var scope = angular.element(element).scope(); 
scope.$apply(...); 

I have looked all over for a solution to do this in Angular(4+) but have only found solutions that work in the app like(Triggering Angular2 change detection manually). I need something that works from the console.

I'm sure I'm doing it wrong but trying to apply the answer on the above question didn't work. I tried many variations of this:

ng.probe($0).injector.view.root.ngModule.injector.get('ApplicationRef')
like image 571
Ryan Avatar asked Jun 30 '17 04:06

Ryan


People also ask

What triggers Angular change detection?

By default, angular will run the change detector every time @Input() data is changed or modified. But with OnPush strategy, the change detector is only triggered if the data passed on @Input() has a new reference.

How does Angular detect change detection?

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.

Does Async pipe triggering change detection?

It means that the component with the async pipe will be marked for check every time a new value is emitted. And Angular will check the component next time it runs change detection even if the value hasn't changed.

How do you use change detection OnPush?

The main idea behind the OnPush strategy manifests from the realization that if we treat reference types as immutable objects, we can detect if a value has changed much faster. When a reference type is immutable, this means every time it is updated, the reference on the stack memory will have to change.


2 Answers

I usually do it as follows in dev mode

ng.probe(getAllAngularRootElements()[0]).injector.get(ng.coreTokens.ApplicationRef).tick()

enter image description here

Starting with Angular 9 with Ivy you can call:

ng.applyChanges(ng.getComponent($0))

Where $0 points to component's element

enter image description here

like image 121
yurzui Avatar answered Sep 20 '22 17:09

yurzui


Solution 1:
1. Click on the element (on which you want to trigger change detection) in the dev-tools Elements-Tab
2. ng.probe($0).injector.get(ng.coreTokens.ApplicationRef).tick()

Solution 2: Trigger a specific components change detector
1. Click on the element (on which you want to trigger change detection) in the dev-tools Elements-Tab
2. ng.probe($0).componentInstance.cdRef.detectChanges()

like image 33
Ilker Cat Avatar answered Sep 19 '22 17:09

Ilker Cat