【问题标题】:How to add component html in existing Angular component如何在现有的 Angular 组件中添加组件 html
【发布时间】:2019-09-18 20:24:39
【问题描述】:

我的 Angular 应用程序中有一个应用程序组件。

@Component({
    selector: my-container',
    template: `<div [innerHTML]="infoComponentHtml"></div>`
})
export class MyContainerComponent implements AfterViewInit {

    @Input() infoComponentHtml: string = "";

    constructor(private componentFactoryResolver: ComponentFactoryResolver){

    }

    ngAfterViewInit(): void {
        if(this.infoComponentHtml){
            ??????
            append this.infoComponentHtml dynamically
        }
        else{
            ??????
            append "<default-content></default-content>" dynamically
        }
    }
}

this.infoComponentHtml 格式是这样的"&lt;component-name&gt;&lt;/component-name&gt;"

this.infoComponentHtml 是来自另一个组件的第三方组件。所以我不知道它的组件类名。

如何编译和添加附加组件?

【问题讨论】:

    标签: angular angular7


    【解决方案1】:

    可以使用结构指令*ngIf:

    HTML:

    <ng-container *ngIf="showInfoComponent; else defaultContent">
        <infoComponent></infoComponent >
    </ng-container>    
    <ng-template #defaultContent>
        <default-content></default-content>
    </ng-template>
    

    更新:

    您无法使用innerHTML 加载组件。为了动态加载组件,需要将组件infoComponentHtml设置为Type&lt;Component&gt;

    @Input() infoComponentHtml: Type<Component>;
    

    然后使用this answer to load component dynamically

    【讨论】:

    • 我需要 AfterViewInit
    • 我无法从字符串中设置&lt;infoComponent&gt;&lt;/infoComponent&gt;。发生模板解析错误
    • @barteloma 你知道选择器名称吗?
    猜你喜欢
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 2019-03-28
    • 2018-10-03
    • 1970-01-01
    • 2019-04-15
    相关资源
    最近更新 更多