动态插入组件到html [英] Insert component into html dynamically

查看:18
本文介绍了动态插入组件到html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在一段 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 <p></p>. But not a component like md-spinner. Any thoughts on how to accomplish this?

推荐答案

在 angular 4 中你可以使用 ngComponentOutlet.

In angular 4 you can use ngComponentOutlet.

模板:

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

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

Build dynamic module and component with your template string:

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

这篇关于动态插入组件到html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆