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

标签 angular ng-switch

使用以下 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 ???;
}

最佳答案

因为您有基类,您可以使用文档中描述的一种方法 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;

然后您将能够在 View 呈现后获得选择的组件:

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

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

Example

关于angular - 如何在 Angular 2 中的 ngSwitchCase 之后获取对组件的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48395238/

相关文章:

javascript - 如何在没有删除按钮的情况下获得第一个修订版?

angular - 两种方式绑定(bind)不适用于 Angular 为 2 的原始对象

javascript - 如何定位和修改 Ionic/Angular 应用程序中 CSS 元素的所有实例?

css - 元素没有在 Angular 中居中

angular - 在使用 ngx-img-cropper 的 Angular 中,如何获取裁剪后的 jpg 或 png 文件,而不是 base64 图像

angularjs - 使用 Ionic 中的 ElementRef 将映射加载到 ngSwitch 子范围

javascript - 带有 typeof 表达式的 ng-switch

angular - 错误: both async and sync fetching of the wasm failed

javascript - ng-switch 在 ng-repeat Angularjs 中

javascript - 最佳实践 : Should I use ng-switch for this?