【问题标题】:Angular function is called hundred of times on mouse moveAngular 函数在鼠标移动时被调用数百次
【发布时间】:2020-07-10 15:31:52
【问题描述】:

我有以下代码,其中包含多选列的材料表。我注意到的是,每次鼠标移动 isAllSelected() 都会被调用数百次。为什么会这样。我认为只有在单击复选框时才应该调用它

<mat-table #table [dataSource]="dataSource">
  <!-- Checkbox Column -->
  <ng-container matColumnDef="checkbox">
    <mat-header-cell *matHeaderCellDef>
      <mat-checkbox (change)="$event ? masterToggle() : null" [checked]="selection.hasValue() && isAllSelected()">
      </mat-checkbox>
    </mat-header-cell>

    <mat-cell *matCellDef="let priority">
      <mat-checkbox (click)="$event.stopPropagation()" (change)="$event ? selection.toggle(priority) : null"
        [checked]="selection.isSelected(priority)">
      </mat-checkbox>
    </mat-cell>
  </ng-container>

  <!-- Colour Column -->
  <ng-container matColumnDef="colour">
    <mat-header-cell *matHeaderCellDef>Colour</mat-header-cell>
    <mat-cell *matCellDef="let priority">{{priority?.colour}}</mat-cell>
  </ng-container>

  <!-- Name Column -->
  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
    <mat-cell *matCellDef="let priority">{{priority?.name}}</mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let priority; columns: displayedColumns;" class="contact" (click)="selection.toggle(row)">
  </mat-row>
</mat-table>

和 .ts 文件

export class AdminPrioritiesSettingsComponent {

 dataSource: MatTableDataSource<any>;

 selection = new SelectionModel<PriorityDto>(true, []);
 displayedColumns = ['checkbox', 'colour', 'name'];


 isAllSelected() {
    console.log(this.selection.hasValue());
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  /** Selects all rows if they are not all selected; otherwise clear selection. */
  masterToggle() {
    this.isAllSelected() ?
      this.selection.clear() : this.dataSource.data.forEach(row => this.selection.select(row));
  }
}

【问题讨论】:

  • 不确定是否相关,但 (change)="$event ? 应替换为 (change)="$event.checked ?。布尔状态包含在事件对象的checked 属性中。
  • @ShubhamBhokare 我从官方角度材料示例中得到了这个例子
  • @pantonis:你能链接那个例子吗?
  • 浏览我上面分享的中篇文章。它有 2 种策略,任何一种都可以在您的代码中使用。

标签: angular typescript angular-material angular8


【解决方案1】:

如果我理解你的代码,isAllSelected() 函数是通过masterToggle() 调用的。 $event 的变化是由您的鼠标移动触发的,因此调用了masterToggle()。这是你的问题吗?在这种情况下,您可能想订阅点击事件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-29
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 2018-11-16
    • 2020-06-26
    • 1970-01-01
    • 2017-04-02
    相关资源
    最近更新 更多