首页 > 解决方案 > 如何在单击时调用一个函数,但在第二次单击(相同按钮)时调用另一个函数?角

问题描述

我想动态单击以调用一个函数和另一个函数。这是一半的工作,但我需要最好的方法来做到这一点。查看我的代码,我会进一步解释。

我的 html 表函数:

<ng-container matColumnDef="country" >
  <mat-header-cell *matHeaderCellDef (click)="sortingCountryTableAsc() ? sortingCountryTableAsc() : sortingCountryTableDesc()"> Country </mat-header-cell>
  <mat-cell *matCellDef="let element"> {{element.country}} </mat-cell>
</ng-container>

我的 ts 文件:

  sortingCountryTableAsc(){
    this.country.sortCountryAsc().subscribe(data => {
      this.allCountry = data;
      this.CountryDataSource.data = this.allCountry;
    })
  }

  sortingCountryTableDesc() {
    this.country.sortCountryDesc().subscribe(data => {
      this.allCountry = data;
      this.CountryDataSource.data = this.allCountry;
    })
  }

Okey onclick 函数我想调用一个函数,然后在另一个单击调用第二个函数。我知道我在 Angular 材料中有排序功能,但我不想使用它。

标签: javascriptangularangular-material

解决方案


尝试这样的事情:

<ng-container matColumnDef="country" >
  <mat-header-cell *matHeaderCellDef (click)="getDataForSort()">
    <span *ngIf="sortAsc">
      &uarr;
    </span>
    <span *ngIf="!sortAsc">
      &darr;
    </span>
    Country 
  </mat-header-cell>
  <mat-cell *matCellDef="let element"> {{element.country}} </mat-cell>
</ng-container>
public sortAsc = true;
...
getDataForSort() {
  // filp asc and desc
  this.sortAsc = !this.sortAsc;
  const dataSource$: any;
  if (this.sortAsc) {
    dataSource$ = this.country.sortCountryAsc();
  } else {
    dataSource$ = this.country.sortCountryDesc();
  }
  dataSource$.subscribe(data => {
      this.allCountry = data;
      this.CountryDataSource.data = this.allCountry;
    });
}

推荐阅读