1

I have an app component in my angular application.

@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 format is like this "<component-name></component-name>"

this.infoComponentHtml is third party component that comes from another component. So I do not know the component class name of it.

How can I compile and add append the component?

barteloma
  • 6,403
  • 14
  • 79
  • 173

1 Answers1

0

It is possible to use structural directive *ngIf:

HTML:

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

UPDATE:

You cannot load components using innerHTML. In order to load components dynamically, you need to set component infoComponentHtml to Type<Component>;

@Input() infoComponentHtml: Type<Component>;

and then use this answer to load component dynamically

StepUp
  • 36,391
  • 15
  • 88
  • 148