【问题标题】:@ViewChild within ngSwitch is undefinedngSwitch 中的@ViewChild 未定义
【发布时间】:2019-03-15 20:49:57
【问题描述】:

我正在尝试访问一些嵌套结构指令中的模板引用:

  <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 中获取对当前切换组件的引用?

【问题讨论】:

  • 有多少个面板可见?
  • 只有一个[ngSwitch]="currentIndex"。如果我删除对@ViewChild 的访问权限,我可以循环浏览面板。
  • 试试@ViewChild(WizardPanelComponent) currentPanel: WizardPanelComponent;
  • 你在每次迭代中重新定义 #visiblePanel 变量,看起来很奇怪
  • 我确实尝试过,为了理智,我又运行了一次,但仍然未定义。

标签: angular


【解决方案1】:

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

【讨论】:

  • 这是一个很好的简化,但它并没有解决未定义的问题。我仍然无法选择带有 ref 或 type 的组件出口。
猜你喜欢
  • 2019-06-23
  • 2021-07-26
  • 2017-03-11
  • 2023-03-21
  • 2019-10-03
  • 2018-05-14
  • 1970-01-01
  • 2018-10-25
  • 1970-01-01
相关资源
最近更新 更多