0

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?

2

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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>

3 Comments

OP does not want to make a method.
Yeah I know this one. But I don't want to call a method from typescript file. Please read the question again
Sorry, I missed that part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.