动态插入组件到html中

mum*_*ilk 5 html angular-material angular

我试图在一段 html 中动态插入一个角度材料组件。我认为,我将无法使用ViewContainerRef

下面是它需要如何工作:

我将从数据库中检索一个字符串(它可以是任何材料组件,例如输入、按钮等......如下所示:

let stringFromDB = "<md-spinner></md-spinner>"
Run Code Online (Sandbox Code Playgroud)

我需要将此字符串传递给我的 html 的 div (这是我的“容器”)。所以我尝试过:

@Component({
    selector: 'report',
    template: `<div [innerHtml]="stringFromDB"></div>`
})
export class ReportComponent{
    stringFromDB : string = null;

    constructor(){  
        this.stringFromDB =this.someService.getTemplateStringFromDatabase();
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以通过一个简单的<p></p>. 但不是像 md-spinner 这样的组件。关于如何实现这一目标有什么想法吗?

mch*_*han 4

在 Angular 4 中,您可以使用 ngComponentOutlet。

模板:

<ng-container *ngComponentOutlet="dynamicComponent; ngModuleFactory: dynamicModule;"></ng-container>
Run Code Online (Sandbox Code Playgroud)

使用模板字符串构建动态模块和组件:

import { Compiler } from '@angular/core';

build() {
    this.dynamicComponent = this.createDynamicComponent(this.stringFromDB);
    this.dynamicModule = this._compiler.compileModuleSync(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;
}
Run Code Online (Sandbox Code Playgroud)