我想将 string
中的 加载或编译 Angular 元素作为 HTML
到我的组件中。
我从 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);
});
但它输出为而不是 ngFor
循环,它只是作为字符串加载。
Load Dynamic HTML
Testing here
{{i}}
上面只是示例 HTML 字符串。它可以是来自服务器的任何内容,例如 ngIf 或任何其他内置的 Angular 指令
我也尝试过使用自定义元素createCustomElement
,但我也无法从字符串渲染Angular指令运行时
。
编辑 1
类似的事情对于 This stackblitz 运行良好。示例,但如果我下载并在本地运行相同的错误。
最佳答案
我在 stackblitz 下载了示例并让它发挥作用。您可以在这里看到完整的代码 - https://github.com/phalgunv/Angular-Dynamic-Component-From-String
它需要进行一些修复才能使其适用于产品构建。
关于javascript - Angular 13 从 HTML 字符串加载/编译动态 Angular 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73269391/