首页 > 解决方案 > 使用 @ViewChild 获取时获取 undefined 的值元素?

问题描述

我的问题是:

角 11.0.0 角-gridster2 11.1.5

无法使用 ViewChild 装饰器访问 gridster-item 元素

使用@ViewChild 获取元素时获取未定义的值?html

<mat-dialog-content #dialogContent2  style="height: 38vw !important; max-height: 38vw !important;">

  <mat-tab-group id="tabGroup" #tabGroup2 (selectedTabChange)="changedOptions(tabGroup)" animationDuration="0ms" mat-align-tabs="center">
    <mat-tab #tap2 *ngFor="let dashboard of dashboards.tabs; index as tapIndex" [label]="dashboard.name">

      <div #div2 dir="ltr" class="certificateBox" [style.width.mm]="dashboards.view.width" [style.height.mm]="dashboards.view.height" >   
        <gridster #gridster2 [options]="options">
          <gridster-item #gridsterItem2 id="gridsterItem" style="background: none;" [item]="item" *ngFor="let item of dashboard.details.contents; index as i">
          </gridster-item>
        </gridster>
      </div>
    </mat-tab>
  </mat-tab-group>
</mat-dialog-content>

打字稿

@ViewChild('dialogContent2')  dialogContent2;
@ViewChild('tabGroup2')  tabGroup2;
@ViewChild('tap2')  tap2;
@ViewChild('div2')  div2;
@ViewChild('gridster2')  gridster2;
@ViewChild('gridsterItem2')  gridsterItem2;

ngAfterViewInit(){

  console.log(this.dialogContent2)) /* works finke */
  console.log(this.tabGroup2)) /* works finke */
  console.log(this.tap2)) /* works finke */
  console.log(this.div2)) /* works finke */
  console.log(this.gridster2) /* works finke */
  console.log(this.gridsterItem2) /* undefined */
}

标签: javascriptangular

解决方案


有问题的组件是ngFor您应该使用它的一部分:

@ViewChildren('gridsterItem2') gridsterItem2: QueryList<GridsterItem>

在您的代码中,请记住它是一个可迭代的(集合)。


推荐阅读