Home > Software engineering >  How to execute javascript code on angular2 html template
How to execute javascript code on angular2 html template

Time:11-08

How to execute javascript code like JSON.parse() in the angular html template itself instead of making a method and calling the method in the angular html template file

I tried below ways:

<p [innerHTML]="JSON.parse(['\\u2013'])[0]"></p>

<p>{{ JSON.parse(['\\u2013'])[0] }}</p>

But getting Property 'JSON' does not exist on type 'AppComponent'.

Can it be possible to write javascript code on angular html template itself?

CodePudding user response:

All you write in .html should be a "public" (variable or object or function). So, we can not use, e.g. {{Math.random()}} nor {{JSON.parse('["\\u2013"]')[0]}} or {{Array.from('foo')}}

See the quotes in JSON.parse

Well, you always can assign a public variable in your .ts (by defect all the variables are public) to the javascript object you want

//declare in your .ts (I choose give the same "name" to the variable)
JSON:any=JSON
Math:any=Math
Array:any=Array

And use in .html

<div>
   {{Math.random()*10}}
   {{JSON.parse('["\\u2013"]')[0]}}
</div>
<div *ngFor="let a of Array.from('foo')">Hello</div>

BTW, if you want to execute javascript, I suggest executed in ngOnInit or ngAfterViewInit functions

CodePudding user response:

You can put your code inside a function in you component.ts file and then call that function from html file.

component.ts

parseJson(data) {
  return JSON.parse(data);
}

component.html

<p>{{parseJson(['\\u2013'])[0]}}</p>
  • Related