【问题标题】:How to get a reference to the component after ngSwitchCase in Angular 2?如何在 Angular 2 中的 ngSwitchCase 之后获取对组件的引用?
【发布时间】:2018-07-01 21:22:02
【问题描述】:

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

【问题讨论】:

    标签: angular ng-switch


    【解决方案1】:

    由于您有基类,您可以使用文档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

    【讨论】:

    • 啊酷。我会像你说的那样尝试,在这种情况下我的组件都是从同一个基类扩展而来的。你会为不同类的组件提供更通用的方法吗?或者@ViewChild 是否仍然能够找到 ngSwitchCase 选择的组件?
    • ViewChild 只会找到那些符合我们在 ViewChild 装饰器中指定的标记的实例。另见stackoverflow.com/questions/39908967/…
    猜你喜欢
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2017-04-15
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多