Here is the NgComponentOutlet
usage example. Let say you have two components:
@Component({
selector: 'dynamic-component-one',
template: `<p>I'm the Component 1</p>`
})
export class FirstDynamicComponent {}
@Component({
selector: 'dynamic-component-two',
template: `<p>I'm the Component 2</p>`
})
export class SecondDynamicComponent {}
The component below loads the FirstDynamicComponent
by default but replaces it with the SecondDynamicComponent
if you click a button:
@Component({
selector: 'my-app',
template: `
<button (click)="switchComponents()">Swith Components:</button>
<ng-container *ngComponentOutlet="content"></ng-container>
`
})
export class AppComponent {
comp1 = FirstDynamicComponent;
comp2 = SecondDynamicComponent;
content = this.comp1;
switchComponents() {
this.content = this.comp2;
}
}
Don't forget to register both dynamic components in their module's entryComponents
section:
@NgModule({
imports: [...],
declarations: [
AppComponent,
FirstDynamicComponent,
SecondDynamicComponent
],
entryComponents: [
FirstDynamicComponent,
SecondDynamicComponent
]
})
export class AppModule { }
StackBlitz example