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,
{{this.prop}}
]]' to identify and iterate over arrays, and I had to specify this to the people who are preparing the strings that are sent from the server. Not to mention it will break if the string contains '[[' or '::' or '{{' etc normally without referencing a variable. I was hoping the angular team has made some provision for cases like this. – Mitth'raw'nuruodo Feb 25 '20 at 07:02