首页 > 解决方案 > 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;

我也尝试过idComponent选择器。基本上,它总是未定义的:

  // Button press
  onNext() {
    this.data = this.currentPanel.data;  // this.currentPanel is undefined
    ...
  }

有没有办法在 ts 中获得对当前切换组件的引用?

标签: angular

解决方案


首先你不需要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>

推荐阅读