[英]How to create a dynamic html template with template literals and *ngFor in Angular
I have been working on a toast component which will accept html tags as string.我一直在研究一个 toast 组件,它将接受 html 标签作为字符串。 Hence I need to loop through below errorMsgs array and build a list dynamically, but the problem is I have a *ngFor inside that and it's looping the array, but I'm not able to print "msg" in the template.
因此,我需要遍历 errorMsgs 数组并动态构建一个列表,但问题是我在里面有一个 *ngFor 并且它正在循环数组,但我无法在模板中打印“msg”。
Please tell me if there is a way to loop through array and build a list and return it as a string.请告诉我是否有办法循环遍历数组并构建一个列表并将其作为字符串返回。
const errorMsgs = ['Not Found', 'Server Error'];
private getMessagesAsHtml(errorMsgs: string[]){
return `
<ul>
<li *ngFor="let msg for ${errorMsgs}">
{{msg}}
</li>
</ul>
`;
}
Finally I solved it using ES6 only.最后我只使用 ES6 解决了它。
const errorMsgs = ['Not Found', 'Server Error'];
private getMessagesAsHtml(errorMsgs: string[]){
return `
<ul>
${errorMsgs.map(msg => `
<li> ${msg} </li>
`)}
</ul>
`;
}
I think instead of我认为而不是
<li *ngFor="let msg for ${errorMsgs}">
{{msg}}
</li>
You should use it like this:你应该像这样使用它:
<li *ngFor="let msg of ${errorMsgs}">
{{msg}}
</li>
Hope it helps!!希望能帮助到你!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.