如何解决Angular 10:如何创建动态Component / 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);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。