如何在 Angular 2 中的 ngSwitchCase 之后获取对组件的引用?

How to get a reference to the component after ngSwitchCase in Angular 2?

与以下 html:

<div [ngSwitch]="type">
    <my-component-a *ngSwitchCase="'A'"></my-component-a>
    <my-component-b *ngSwitchCase="'B'"></my-component-b>
    <my-component-c *ngSwitchCase="'C'"></my-component-c>
    <my-component-d *ngSwitchDefault></my-component-d>
</div>

如何在 ts 代码中获取对所选组件的引用?例如

public getChosenComponent(): MyComponentBase {
    return ???;
}

因为你有基础 class 你可以使用文档中描述的一种方法 https://angular.io/guide/dependency-injection-in-action#find-a-parent-by-its-class-interface

您需要为所有应该是所选组件的组件提供 MyComponentBase。例如,CompB 可以声明如下:

@Directive({
  selector: 'my-component-b',
  providers: [{ provide: MyComponentBase, useExisting: CompB }]
})
export class CompB {}

现在您需要使用 @ViewChild 装饰器查询所选组件:

@ViewChild(MyComponentBase) component: MyComponentBase;

然后您将能够在视图渲染后获得选择的组件:

getChosenComponent(): MyComponentBase {
  return this.component;
}

ngAfterViewInit() {
  console.log(this.getChosenComponent());
}

Example