2
votes

I am new to angular. I am trying render some dynamic template strings that are coming from a server in a component.

The component looks like this -

<div [innerHTML]='templateString'></div>

In component.ts file, we have

obj = {
   prop: 'text to display'
}
templateString = '<p class="text-primary">{{obj.prop}}</p>' // this is dynamic, e.g. received from an http request

If we leave it like this, it will render as '{{obj.prop}}' whereas I want it to show is 'text to display'. Currently I have written a script that takes the templateString and obj and returns the properties by using .split('{{') etc. Is there some simpler built-in way to do this in angular? I.e. compiling the template strings dynamically onChanges or onInit, so that I can take advantage of ngFor to display values inside an array property for instance.

arr = [
   {prop: 'text1'},
   {prop: 'text2'}
]
templateString = '<p *ngFor="let item of arr">{{item.prop}}</p>'

Currently I am using a custom syntax [[arr::

{{this.prop}}

]] which my script can read and iterate over arrays, but it is pretty unreliable and non standard.

I have seen this Angular: bind variables inside [innerHtml], but it seems overqualified since I do not need to put other components inside the template string. Just standard html, with some directives like ngFor, ngIf etc,

2
Interpolation {{}} is used on HTML, on TS you can assign value to templateString by obj.propMridul
Yeah .. you just need to do templateString = obj.prop.jophab
Change '{{obj.prop}}' to this.obj.prop like, templateString = this.obj.prop , Example: stackblitz.com/edit/my-angular-starter-cnp4yjManiraj Murugan
Does this answer your question? Angular 2 innerHTML ignoring form tagsvicpermir
templateString is expected to contain html. I have updated my question. Using this.obj.prop will not work in this case.Mitth'raw'nuruodo

2 Answers

0
votes

I think you can just use inline concatenation

`this is the string ${this.foo} more string here`
0
votes

No rocket science needed. This will work for you!

templateString = '<p class="text-primary">'+  this.obj.prop + '</p>' ;