首页 > 解决方案 > 动态排序但变量名未定义

问题描述

我需要使用按钮设置动态排序数据表。当我单击按钮对其进行排序时,会出现这样的错误。 ERROR TypeError: "this.aName is undefined". 然而,我首先像这样声明它@ViewChild('aName') aName:ElementRef;。我已经提供了完整的代码供您参考。

HTML

<mat-chip (click)="test('aName')">
 <mat-icon class="icon icon-filter"></mat-icon>Sort
</mat-chip>

组件 ts

@ViewChild(MatSort) sort: MatSort;
@ViewChild('aName') aName:ElementRef;

test(val){
  console.log(val)
  switch(val) {
    case "aName": { 
      this.aName.nativeElement.click()
      this.aName.nativeElement.click()            
      break; 
      } 

  }
  this.Nameservice.getNameService(this.pageIndex).subscribe(res =>{
    console.log(this.pageIndex)
    this.dataSource = new MatTableDataSource<NameDetails>(res);
    this.dataSource.sort = this.sort;

    const sortState: Sort = {active: val, direction: this.sort.direction === 'asc' ? 'desc' : 'asc'};
    this.sort.direction = sortState.direction;
  this.sort.sortChange.emit(sortState);

  });
}

ngAfterViewInit() {
  this.sort.sortChange.subscribe((x) => {
    console.log(x);
  });
}

希望大家能帮忙

提前致谢

标签: angulartypescriptsorting

解决方案


您需要在 HTML 中设置模板引用变量( #aName) 以便将其与命名选择器一起使用。你可以这样做:

<mat-chip (click)="test('aName')" #aName>
 <mat-icon class="icon icon-filter"></mat-icon>Sort
</mat-chip>

但我不明白你为什么要这样做this.aName.nativeElement.click(),为什么要两次。这将创建一个无限循环。


推荐阅读