[英]Angular 13 load/compile dynamic Angular component from HTML string
I want to load or compile Angular elements as HTML
from string
into my component.我想将
Angular elements as HTML
从string
加载或编译到我的组件中。
I am getting HTML string from API as a string and I want to load and render all HTML structural directives from that string.我从 API 获取 HTML 字符串作为字符串,我想从该字符串加载和渲染所有 HTML 结构指令。
let str = `<div>Testing here
<div *ngFor="let i of [1,2,3,4]">{{i}}</div>
</div>`;
setTimeout(() => {
const componentRef: ComponentRef<DynamicComponent> =
this.createDynamicComponent<DynamicComponent>(
DynamicComponent,
this.vc
);
componentRef.instance.html = this.sanitizer.bypassSecurityTrustHtml(str);
});
But it output as instead of ngFor
loop it simply loads as string.但它是 output 而不是
ngFor
循环,它只是作为字符串加载。
Load Dynamic HTML
Testing here
{{i}}
Here is sample I tried 这是我试过的样本
Here above is just sample HTML string.以上只是示例 HTML 字符串。 It can be anything from server like
ngIf
or any other inbuilt Angular
directives它可以是来自服务器的任何东西,如
ngIf
或任何其他内置Angular
指令
I have also tried using custom element createCustomElement
but in that also I was not able to render Angular directives runtime from string
.我也尝试过使用自定义元素
createCustomElement
但我也无法Angular directives runtime from string
。
Edit 1编辑 1
Similar thing is working fine for This stackblitz example but If I download and run locally same error.对于这个 stackblitz示例,类似的事情工作正常,但如果我下载并在本地运行同样的错误。
I downloaded the example at stackblitz and got it working.我在stackblitz下载了这个例子并让它工作。 You can see the complete code here - https://github.com/phalgunv/Angular-Dynamic-Component-From-String
您可以在此处查看完整代码 - https://github.com/phalgunv/Angular-Dynamic-Component-From-String
It required a couple of fixes needed to get it working for prod build.它需要进行一些修复才能使其适用于产品构建。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.