如何在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代码中获得对所选组件的引用?例如
How do I get a reference to the chosen component inside the ts code? e.g.
public getChosenComponent(): MyComponentBase {
return ???;
}
推荐答案
Since you have base class you could use one method that is described in the docs https://angular.io/guide/dependency-injection-in-action#find-a-parent-by-its-class-interface
您需要在所有应该被选为组件的组件上提供 MyComponentBase
.例如, CompB
可以声明如下:
You need to provide MyComponentBase
on all of your components that are supposed to be a chosen component. For example, CompB
could be declared as follows:
@Directive({
selector: 'my-component-b',
providers: [{ provide: MyComponentBase, useExisting: CompB }]
})
export class CompB {}
现在,您需要使用 @ViewChild
装饰器查询所选组件:
Now you need to query chosen component by using @ViewChild
decorator:
@ViewChild(MyComponentBase) component: MyComponentBase;
然后您将能够在渲染视图之后获得所选组件:
and then you will be able to get choosen component after view has been rendered:
getChosenComponent(): MyComponentBase {
return this.component;
}
ngAfterViewInit() {
console.log(this.getChosenComponent());
}
Example
这篇关于如何在Angular 2中的ngSwitchCase之后获取对组件的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!