How to breakpoint and debug angular templates?

Viewed 16600

For example, in React you can put a breakpoint in your view/template and check what is going on.

Edit: Let's say I want to see what is going on here:

<h2>{{hero.name | uppercase}} Details</h2>
<div><span>id: </span>{{hero.id}}</div>
<div>
  <label>name:
    <input [(ngModel)]="hero.name" placeholder="name">
  </label>
</div>

https://stackblitz.com/angular/kopjlplrpanj?file=src%2Fapp%2Fheroes%2Fheroes.component.html

I want to inspect the variables in the scope of this template. See their values.

2 Answers

Someone can say that debugging templates will come with Ivy but I would say that we can also easy debug current View Engine.

For example, here are some options I would use:

1) Angular generates ngFactory for each component which can be found by path ng://ModuleName/ComponentName.ngfactory.js.

Each factory contains two methods updateDirectives and updateRenderer where you can debug your variables.

enter image description here

2) Make some mistake in template

<h2>{{herox.name | uppercase}} Details</h2>
         ^^^^

Now you can find the target place in your console

enter image description here

3) Put the following code at the beginning of your template

<ng-container *ngIf="1; let x='ngIf; debugger'">{{x}} 

And you will automatically moved to updating template code

enter image description here

For more info see

Update:

I agree that it's hard to understand the generated code so that in simple cases you do not need that and you can just look at the value through printing it somewhere, i.e:

{{myVar}}

or

<div [attr.debug-var]="someVar">

Update 2

{{ this.constructor.__proto__.constructor('', 'debugger')() }}

https://twitter.com/yurzui/status/1179436748826394626

You can do the below steps:

  1. Open Developer Console
  2. Goto: Sources tab
  3. Goto Sub tab: Page
  4. You generally have your angular project files in webpack:// or ng:// or such related menuItem folder, find your Angular project files.
  5. Then, find your Template file
  6. Attach a Breakpoint on the line on which you want to the see data, and
  7. Reload your page Or Execute that part of the code or Execute the Event for that code (If that part of the code runs on a Button click or mouse hover, Go ahead and click the button or hover mouse)
  8. You will generally see your Data in the _co field of the Breakpoint Scope

enter image description here

Related