簡體   English   中英

角度動態注入特定組件

[英]Angular dynamically inject specific component

我有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中執行此操作的最佳實踐

這是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其替換為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示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM