Sub topic 11
Combining DevTools with the console's ng utilities
This chapter assumes you can already open the Angular DevTools tab, select a component in the component tree, and read its properties. It also assumes you are comfortable with $0 and console.log in the browser console, and that your app runs in development mode. The goal is to use the panels and the console together, because each is faster at some jobs.
Why use the console when the panels exist
Angular DevTools is good at browsing. It shows the whole tree, highlights the selected component, and lets you edit simple values. The console is good at querying, scripting, and comparing. For example, you can ask "which directives sit on this element?" or "does this button have a click listener?", and you can run a one-line loop over many elements.
In development mode, Angular adds a global object named ng to the page. Its functions read the same runtime data that DevTools shows. DevTools relies on the same debugging information that these functions expose, so a value you read in the console should match what the panel displays.
Requirements and limits
- The
ngglobal exists only in development builds. In a production build,ngisundefined. If you typengand getReferenceErrororundefined, check that you are serving the dev build. - Each function takes a DOM element or a component or directive instance. Passing an element that Angular does not manage gives
nullor an empty array, not an error. - The functions are debugging aids. Do not call them from application code, and do not depend on them in tests that run against production builds.
The main ng functions
| Function | Input | Returns |
|---|---|---|
| `ng.getComponent(element)` | DOM element | The component instance attached to that element, or `null` |
| `ng.getOwningComponent(elementOrDir)` | Element or directive | The component whose template contains it |
| `ng.getRootComponents(elementOrDir)` | Element or directive | The root components of the app that contains it |
| `ng.getDirectives(element)` | DOM element | An array of directive instances on that element |
| `ng.getHostElement(componentOrDir)` | Instance | The DOM element hosting that instance |
| `ng.getContext(element)` | DOM element | The context object of the embedded view around the element, such as the loop item |
| `ng.getListeners(element)` | DOM element | An array of listener records for that element |
| `ng.getInjector(elementOrDir)` | Element or directive | The injector that applies at that location |
| `ng.getDirectiveMetadata(instance)` | Instance | Metadata such as inputs, outputs, and the component's change detection strategy |
| `ng.applyChanges(component)` | Component instance | Nothing. It runs change detection for that component |
Check the exact list in your Angular version by typing ng. in the console and reading the autocomplete suggestions. The set has grown across releases.
Getting a reference to start from
Every call needs an element or an instance. The quickest way to get one is the $0 variable. Chrome and Firefox set $0 to the node currently selected in the Elements panel. So the workflow is:
- Find the component in the Angular DevTools tree. Use the "inspect element" control or the highlight to confirm which DOM node it is.
- Switch to the Elements panel and select that node, or click the element on the page with the element picker.
- In the console, call
ng.getComponent($0).
If $0 points at a child element inside the component, such as a <p> in its template, ng.getComponent($0) returns null, because that element is not a host. Use ng.getOwningComponent($0) in that case.
Walkthrough: reproducing a state without clicking
Use the ReportComponent from the previous chapters. After changing it to OnPush with a rows signal, you want to see how the page looks with only ten rows, without editing the source.
// $0 is the <app-report> element selected in the Elements panel.
const cmp = ng.getComponent($0);
// Inspect the current state first.
console.log(cmp.rows().length); // 500
// Replace the data. rows is a signal, so use set().
cmp.rows.set(cmp.rows().slice(0, 10));
// Ask Angular to re-render this component and its children.
ng.applyChanges(cmp);Calling cmp.rows.set(...) changes the data, and ng.applyChanges(cmp) makes sure the view is refreshed. With a signal read in the template, the set alone often refreshes the view. Calling applyChanges anyway is harmless and keeps the same script working for plain properties.
For the earlier default-strategy version, rows is a plain array. There you assign it directly and then call applyChanges:
const cmp = ng.getComponent($0);
cmp.rows = cmp.rows.slice(0, 10);
ng.applyChanges(cmp);Why a property edit sometimes appears to do nothing
Code you type in the console runs outside Angular's change detection triggers. With Zone.js, a console statement is not wrapped in the Angular zone, so Angular is not told that something changed. A default-strategy component may refresh on the next unrelated event, which looks random. An OnPush component will not refresh at all until it is marked dirty. ng.applyChanges closes that gap. When an edit does not show, call it before assuming your logic is wrong.
Inspecting an element in detail
Suppose a button in a list does nothing when clicked. The component tree shows the right component, so the next question is whether the listener is attached and what data the row holds.
const el = $0; // the <button> element
// Which listeners does Angular know about on this element?
ng.getListeners(el).map((l) => l.name); // e.g. ["click"]
// Which directives are applied to it?
ng.getDirectives(el).map((d) => d.constructor.name);
// What data does the surrounding @for or *ngFor item hold?
const ctx = ng.getContext(el);
console.log(ctx);
// Which component's template contains this button?
console.log(ng.getOwningComponent(el));Read the results as follows:
- An empty listener array means the template has no
(click)binding on that element. Check the template for a typo in the event name or a binding on a parent element. getDirectivesshows directives you may not expect, such asRouterLinkor a form directive. This explains behavior like a click that triggers navigation.getContextreturns the view context. For a looped item, the item is usually in$implicit, and the index appears under a name such asindexor$index, depending on whether you use@foror*ngFor. Print it once and look.getOwningComponentanswers "whose template is this?" when you are looking at an element that belongs to a library component's internals.
ng.getListeners reports listeners registered through Angular. A listener added with addEventListener in code will not appear.
Dependency injection from the console
The injector view in DevTools shows which providers a component can see. The console adds a way to ask the injector directly:
const injector = ng.getInjector($0);
console.log(injector);To call injector.get(token), you need the token. Services are classes, and class names are not global variables in the console, so you cannot simply write injector.get(Router). Two workable options exist:
- Use the DevTools injector panel to see which providers exist and at which level they are provided, then reproduce the lookup in application code temporarily.
- Use a string or
InjectionTokenthat you have already attached towindowfor the debugging session. Remove it before committing.
The first is safer because it leaves no debugging code in the project.
Metadata and change detection strategy
ng.getDirectiveMetadata is useful during profiling. If a component you expected to be OnPush is re-rendering on every cycle, check what Angular recorded:
const meta = ng.getDirectiveMetadata(ng.getComponent($0));
console.log(meta);Look at the returned object for the inputs, outputs, and the change detection setting. If it shows the default strategy where you expected OnPush, you have found the problem without reading source. Fields available differ by version, so print the whole object once and read it.
Choosing between the panels and the console
Common errors
ng is not defined. You are on a production build, or the page has not finished bootstrapping. Reload on the dev server and wait for the app to render.ng.getComponent($0)returnsnull. The selected node is not a component host. Select the host element, or usegetOwningComponent.$0is stale. It holds the last selected node. If you click in the Angular DevTools tab, the Elements selection does not change, so re-select the node first.- Edits disappear. A change to a value that is derived or re-bound from a parent input is overwritten on the next parent update. Edit the source of the value instead, such as the parent's property.
- Changing a computed signal. A
computedsignal is read-only, so it has noset. Set the writable signal it depends on.
A combined routine
- Use the component tree to find the component and its position in the hierarchy.
- Read its inputs and state in the properties panel.
- Select its host element in the Elements panel and run
ng.getComponent($0)to get a reference you can script. - Change the state with a property assignment or
signal.set, then callng.applyChanges. - Check listeners, directives, and context with the
ngfunctions if the behavior still looks wrong. - Record a profile in the Profiler tab if the problem is speed, then compare it with a second profile after your change.
Exercise
You select the <app-report> host element, run ng.getComponent($0), assign cmp.title = 'Test', and the page does not change. The component uses OnPush. What is the likely cause, and what do you run next?
Show answer
The console statement runs outside Angular's change detection triggers, and an OnPush component is not marked dirty by a plain property assignment. Run ng.applyChanges(cmp) to refresh the component and its children.
Exercise
A button inside a list does nothing on click. Which three ng calls help you decide whether the template binding exists, which directives are on the button, and which row it belongs to?
Show answer
ng.getListeners($0) lists the listeners Angular registered, so an empty result means no event binding. ng.getDirectives($0) lists the directives on the element. ng.getContext($0) returns the surrounding view context, which holds the row item for a loop.
Exercise
ng.getComponent($0) returns null while an <p> inside the component's template is selected. Why, and which function gives you the component?
Show answer
A <p> is not a component host element, so no component instance is attached to it. ng.getOwningComponent($0) returns the component whose template contains the element.