Angular动态注入特定组件

时间:2017-11-17 12:13:37

标签: javascript angular

我有3个组件,我想根据从Get请求收到的值将其中一个组件注入另一个组件html:

Comp1,Comp2,Comp3

当前的方式不太理想,特别是当3个组件可能很快变为20

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

使用React我可以通过函数调用轻松地注入JSX,但我不确定在Angular中执行此操作的最佳实践

1 个答案:

答案 0 :(得分:0)

以下是NgComponentOutlet用法示例。假设您有两个组成部分:

@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 {}

下面的组件默认加载FirstDynamicComponent,但如果点击按钮则将其替换为SecondDynamicComponent

@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;
  }
}

不要忘记在模块的entryComponents部分中注册两个动态组件:

@NgModule({
  imports: [...],
  declarations: [ 
      AppComponent,
      FirstDynamicComponent,
      SecondDynamicComponent
  ],
  entryComponents: [
      FirstDynamicComponent,
      SecondDynamicComponent
  ]
})
export class AppModule { }

StackBlitz example