html - Angular 10:如何创建动态组件/html?
问题描述
2个问题:
<div>{{ someData }}</div>
- 如何使{{ someData }}
转换为html?<div>{{ MyComponentClass }}</div>
- 如何使它创建组件MyComponentClass 的实例并将其放入div 中?
对于问题 1,我想我需要一种方法来访问 DOM 元素,然后自己注入它。对于问题 2,我不知道,但它会非常有用。
解决方案
- 问题:
您可以将字符串/html 变量绑定到 [innerHTML] 属性绑定。
<div [innerHTML]="theHtmlString"></div>
如果 html 不起作用,您需要注入 DomSanitizer 来告诉 Angular html 是安全的。
constructor(private sanitizer:DomSanitizer) {
this.htmlString = this.sanitizer.bypassSecurityTrustHtml(style);
}
- 问题:
您可以使用 @ViewChild 动态创建组件并从您的 div 获取 ViewContainerRef 并使用 componentFactoryResolver:
模板:
<div #yourdiv></div>
零件:
@ViewChild("yourdiv" , {read: ViewContainerRef}) private vcr: ViewContainerRef;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
let resolver = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);
let componentFactory = this.vcr.createComponent(resolver);
}
推荐阅读
- java - 更改一个 ViewHolder 项目也会影响其他项目
- node.js - vue create 抛出我无法弄清楚的 651 错误
- mysql - 使用sql查询将带有操作的字符串转换为int
- r - 根据数字输入更改 r 数据表中的列值
- python - Acumos:码头集装箱无法找到文件
- javascript - 在另一个 eventListener 的函数中包含一个 eventListener 是一种不好的做法吗?
- javascript - jQuery DateRangePicker - 更改开始日期时,结束日期也会更改 - 为什么?
- android - 无法使用 FCM 显示 Android Heads Up 通知
- soapui - 在 LoadUI 中创建设置步骤
- python - 如何将我的 python 输出自动保存到 csv