Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to breakpoint and debug angular templates?

Tags:

angular

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.

like image 985
Totty.js Avatar asked Nov 08 '18 04:11

Totty.js


People also ask

How do you breakpoint in debugging?

To set a breakpoint in source code: Click in the far left margin next to a line of code. You can also select the line and press F9, select Debug > Toggle Breakpoint, or right-click and select Breakpoint > Insert breakpoint. The breakpoint appears as a red dot in the left margin.

How do I debug Angular HTML in Chrome?

After editing your default code of App component, serve your app with the following Angular CLI command. This will be your output after changes. Now we need a Google chrome debugger extension for Visual Studio code, so click on extension option at left side icon of VS code.

Can we debug Angular code in browser?

You can debug using browsers built in developer tools. open developer tools in browser and go to source tab. add break point on a line ny clicking on left side of the code. refresh the page.


1 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

  • Catch Angular template errors like a pro or how I create Angular Demo

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

like image 173
yurzui Avatar answered Sep 22 '22 00:09

yurzui