Alex
Alex

Reputation: 11

How to call one function at click but on second click (same button) call another function? Angular

I want to click dynamically to call one function and another. This is halfway work, but I need the best way to do this. Check out my code and I'll explain it further.

my html table function:

<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>

my ts file:

  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 function i want to call one function and on another click call second. I KNOW I HAVE SORT FUNCTION IN ANGULAR MATERIAL BUT I WAN'T USE IT.

Upvotes: 1

Views: 126

Answers (2)

Andrei Voicu
Andrei Voicu

Reputation: 750

you can use a higher order function that can wrap a boolean flag, and depending on a flag, execute a functionality or another:

const toggleFunction = (() => {
  let toggle = true;

  return () => {
   toggle = !toggle;

   console.log(toggle);
  }
})()

toggleFunction()
// false

toggleFunction()
// true

Upvotes: 0

AliF50
AliF50

Reputation: 18849

Try something like this:

<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;
    });
}

Upvotes: 1

Related Questions