问题描述
限时送ChatGPT账号..我正在尝试在一段 html 中动态插入一个 angular-material 组件.我认为,我将无法使用 ViewContainerRef.
I'm trying to insert a angular-material component inside a piece of html dynamically. The way i think, i won't be able to use ViewContainerRef.
以下是它的工作原理:
我将从数据库中检索一个字符串(它可以是任何材料组件,例如输入、按钮等......类似这样:
I'll retrieve a string from the database (it can be any material component, such as inputs, buttons, etc... Something like this:
let stringFromDB = "<md-spinner></md-spinner>"
我需要将此字符串传递给我的 html 的 div(这是我的容器").所以我尝试了:
I would need to pass this string to my html's div (which is my "container"). So i tryied:
@Component({
selector: 'report',
template: `<div [innerHtml]="stringFromDB"></div>`
})
export class ReportComponent{
stringFromDB : string = null;
constructor(){
this.stringFromDB =this.someService.getTemplateStringFromDatabase();
}
}
我可以传递一个简单的
I can pass a simple 在 angular 4 中你可以使用 ngComponentOutlet. In angular 4 you can use ngComponentOutlet. 模板: 使用模板字符串构建动态模块和组件: Build dynamic module and component with your template string: 这篇关于动态插入组件到html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!<p></p>
.
But not a component like md-spinner. Any thoughts on how to accomplish this? 推荐答案
<ng-container *ngComponentOutlet="dynamicComponent; ngModuleFactory: dynamicModule;"></ng-container>
import { Compiler } from '@angular/core';
build() {
this.dynamicComponent = this.createDynamicComponent(this.stringFromDB);
this.dynamicModule = this._compilerpileModuleSync(this.createDynamicModule(this.dynamicComponent));
}
createDynamicModule(componentType: any) {
@NgModule({
imports: [ ],
declarations: [
componentType
],
entryComponents: [componentType]
})
class RuntimeModule { }
return RuntimeModule;
}
createDynamicComponent(template: string) {
@Component({
selector: 'dynamic-component',
template: template ? template : '<div></div>'
})
class DynamicComponent {
constructor() {
}
}
return DynamicComponent;
}
更多推荐
[db:关键词]
发布评论