1

I have 3 components, and I want to inject one of them into another components html based on the values received from a Get request:

Comp1, Comp2, Comp3

the current way is less than ideal, especially when 3 components may soon become 20

  <Comp1 *ngIf="data.value === 'comp_1'"></Comp1>
  <Comp2 *ngIf="data.value === 'comp_2'"></Comp2>
  <Comp3 *ngIf="data.value === 'comp_3'"></Comp3>

With React I can easily inject pieces of JSX via a function call, but I'm not sure on the best practices for doing this in Angular

  • Look at this -> https://angular.io/guide/dynamic-component-loader – Suren Srapyan Nov 17 '17 at 12:15
  • 2
    You can use `ngSwitch` or something like https://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468. See also https://angular.io/api/common/NgComponentOutlet – Günter Zöchbauer Nov 17 '17 at 12:15
  • NgComponentOutlet is a much neater way of doing it, thanks. –  Nov 17 '17 at 12:32

1 Answers1

0

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

hiper2d
  • 2,814
  • 1
  • 18
  • 14