angular - ngSwitch 中的@ViewChild 未定义
问题描述
我正在尝试访问一些嵌套结构指令中的模板引用:
<ng-container [ngSwitch]="currentIndex">
<ng-container *ngFor="let panel of panels; index as panelIndex;">
<ng-container *ngSwitchCase="panelIndex">
<ng-container #visiblePanel *ngComponentOutlet="panel; injector: injector"></ng-container>
</ng-container>
</ng-container>
</ng-container>
我尝试通过以下方式引用该组件:
@ViewChild('visiblePanel') currentPanel: WizardPanelComponent;
我也尝试过id
和Component
选择器。基本上,它总是未定义的:
// Button press
onNext() {
this.data = this.currentPanel.data; // this.currentPanel is undefined
...
}
有没有办法在 ts 中获得对当前切换组件的引用?
解决方案
首先你不需要ngSwitch。所以将代码更改为
<ng-container>
<ng-container *ngFor="let panel of panels; index as panelIndex;">
<ng-container *ngIf="panelIndex === currentIndex">
<ng-container #visiblePanel *ngComponentOutlet="panel; injector: injector"></ng-container>
</ng-container>
</ng-container>
</ng-container>
推荐阅读
- .net - 如何在 C# 7.3 中使引用类型可以为空?
- javascript - 带有js事件源的Flask事件流应用程序覆盖以前的流输出
- python - 带有一系列列表的熊猫的元素明智的“输入”
- coinbase-api - Coinbase API 沙箱不再可用?
- amazon-sns - 将有效模式发布到不存在的主题?
- java - 创建具有多个同名文件的 zip
- javascript - 如何将字符串转换为对象和计数?
- python - 为 AWS Python Lambda 生成私钥以 sftp 到目标主机
- javascript - 正则表达式匹配表达式中包含的整个单词
- r - 如何在德雷克中使用闪亮的应用程序作为目标