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,
templateString = obj.prop
. – jophab'{{obj.prop}}'
tothis.obj.prop
like,templateString = this.obj.prop
, Example: stackblitz.com/edit/my-angular-starter-cnp4yj – Maniraj Murugan