Insert component into html dynamically

2019-04-12 01:49发布

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.

Here's how it needs to work:

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>"

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?

1条回答
Anthone
2楼-- · 2019-04-12 02:29

In angular 4 you can use ngComponentOutlet.

Template:

<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;
}
查看更多
登录 后发表回答