17

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')
3
  • 1
    it doesn't work because you pass a string 'ApplicationRef' instead of a reference to an ApplicationRef class. You need to get reference to the application class like @yurzui showed - ng.coreTokens.ApplicationRef. For more information on debugging, see Everything you need to know about debugging Angular applications Commented Jun 30, 2017 at 4:44
  • Ah I see now. Thanks for the link. Commented Jun 30, 2017 at 16:56
  • I asked the same question, regarding Ivy here: stackoverflow.com/q/59191406/3694288 Commented Dec 5, 2019 at 9:53

3 Answers 3

25

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

Sign up to request clarification or add additional context in comments.

1 Comment

I keep getting back to this page so often :D thanks for response. Plus is there any shortcut ?
8

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()

3 Comments

ng.probe($0).componentInstance.cdRef === undefined
For solution 2: Apparently, to use this*, you must inject the changeDetectorRef into your component, from @angular/core... ( * cdRef being the locally-declared instance of changeDetectorRef )
Greate explanation dude :)
0

@guati I was getting some "Failed to Load Module" error (angular 7), the error was triggered due to some changes in the routing but even when I reverted the changes, the error persisted (may be changes were not being detected) so I just restarted the development server (served the application again) and it went away.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.