简体   繁体   English

角度动态注入特定组件

[英]Angular dynamically inject specific component

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: 我有3个组件,我想根据从Get请求收到的值将其中一个注入另一个html组件中:

Comp1, Comp2, Comp3 Comp1,Comp2,Comp3

the current way is less than ideal, especially when 3 components may soon become 20 当前的方法不太理想,尤其是当3个组件可能很快变为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 借助React,我可以通过函数调用轻松注入JSX片段,但是我不确定在Angular中执行此操作的最佳实践

Here is the NgComponentOutlet usage example. 这是NgComponentOutlet用法示例。 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: 下面的组件默认情况下会加载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;
  }
}

Don't forget to register both dynamic components in their module's entryComponents section: 不要忘记在模块的entryComponents部分中注册这两个动态组件:

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

StackBlitz example StackBlitz示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM