使用以下 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());
}
关于angular - 如何在 Angular 2 中的 ngSwitchCase 之后获取对组件的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48395238/