【问题标题】:Insert component into html dynamically将组件动态插入到 html 中
【发布时间】:2017-09-01 00:22:51
【问题描述】:

我正在尝试在一段 html 中动态插入一个 angular-material 组件。按照我的想法,我将无法使用ViewContainerRef

它的工作原理如下:

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

let stringFromDB = "<md-spinner></md-spinner>"

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

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

    constructor(){  
        this.stringFromDB =this.someService.getTemplateStringFromDatabase();
    }
}

我可以传递一个简单的&lt;p&gt;&lt;/p&gt;。 但不是像 md-spinner 这样的组件。关于如何做到这一点的任何想法?

【问题讨论】:

标签: html angular angular-material


【解决方案1】:

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

模板:

<ng-container *ngComponentOutlet="dynamicComponent; ngModuleFactory: dynamicModule;"></ng-container>

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

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;
}

【讨论】:

    猜你喜欢
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 2019-02-03
    • 2023-03-12
    • 1970-01-01
    • 2017-04-06
    相关资源
    最近更新 更多