Get an instance of the rendered component, in Developer Tools

Photo by Sigmund on Unsplash

Get an instance of the rendered component, in Developer Tools

Debugging in Angular

Do you want to get the component instance that is rendered on the browser? Here is a quick way to do it.

I have a component called HelloComponent and it has a logMessage method inside it. Below is the code:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<h1 (click)="logMessage()">Hello {{name}}!</h1>`
})
export class HelloComponent  {
  @Input() name: string;

  logMessage() {
    console.log('This is a hello component');
  }
}

When this component renders, it shows up as follows:

<hello _ngcontent-avf-c62="" _nghost-avf-c61="" ng-reflect-name="Angular 12">
<h1 _ngcontent-avf-c61="">Hello Angular 12!</h1>
</hello>

This is an HTML output, and although it shows me the actual output of the component, I can't do much with it. I want to get hold of the component instance itself. Below are the steps to get that done:

  1. Click on the html element you want to get an instance of from the Elements tab of the Developer Tools.
  2. On the console, type in the command shown below.
var hello = ng.getComponent($0);

Now you have an instance of the HelloComponent. You can try the following:

hello.logMessage();

You should see the message logged.

Note: Using $0 allows you to get hold of the element that's clicked (selected) on the Elements tab of the developer console.

To update the name input of our component, and have change detection trigger, we can write the following in our console (making sure we have selected the element):

hello.name = 'Updated hello!';
ng.applyChanges($0);

Now our view should show the new value.

Enjoy debugging!