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

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

问题描述

我正在尝试在一块html中动态插入一个角材料组件.我的想法是,我将无法使用 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();
    }
}

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

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天全站免登陆