0
votes

I want to create a dropdown (or mat-select) to use as a sorting mechanism instead of the Angular Material Sort Header. So, if I for example click on the 'username' inside the dropdown, I want the table to sort by the username (instead of clicking on the header).

enter image description here

How can I do it? Any documentation online on how to achieve this?

Thank you for any help.

As required, I attach some code:


  ngOnInit(): void {
    this.filteredOptions = this.myControl.valueChanges.pipe(
      startWith(""),
      map((value) => this._filter(value))
    );
  }

  ngAfterViewInit() {
    this.providersAdmin.sort = this.sort;
  }

  getAllAdmins() {
    this.isLoading = true;
    this.homeService.getAllAdmins().subscribe(
      (response) => {
        this.admins = response;
          this.providersAdmin = new MatTableDataSource(this.admins);
        this.isLoading = false;
      },
      (error) => {}
    );
  }

  sortTableBy(event: any) {
    const sortState: Sort = {
      active: "username",
      direction: "desc",
    };
    this.sort.active = sortState.active;
    this.sort.direction = sortState.direction;
    this.sort.sortChange.emit(sortState);

    console.log(event);
  }

The sortTableBy method is the one I found on here but nothing happens.

I added matSort on the mat-table and I added mat-sort-header on the header cell.

EDIT: Hi, I managed to fix the problem by writing the following:

sortTableBy(event: any) {
    const sortState: Sort = {
      active: "username",
      direction: "desc",
    };
    this.sort.active = sortState.active;
    this.sort.direction = sortState.direction;
    this.sort.sortChange.emit(sortState);
    this.providersAdmin.sort = this.sort;
  }
1
What did you try so far? Show us some code - Gaël J
Well, basically nothing because I don't know how to start. I did use this tutorial htmlgoodies.com/javascript/custom-sort-javascript-tables, and I managed to catch the emit to the MatSort but it didn't update my table. Actually, let me add the code in the main thread for what I have currently. - Mehmed Duhovic
A tip - here is the source of sort function that MatSort uses github.com/angular/components/blob/master/src/material/sort/… - S Overfow
@SOverfow Yeah I assumed that I would have to dig inside the source to find the source of what messed the sort... Will do! - Mehmed Duhovic
Hi, I tried to fix this for a long time until I realized that I just have to reset the new Admins after the sort inside the sortTableBy method. I will post the solution in the OP. Now it works, If anyone else has the same problem! - Mehmed Duhovic

1 Answers

0
votes

There is an example for you: Exmaple

Your sort function has a wrong implementation, this is work for me:

  sortData(fieldName: string) {
    if (!fieldName) {
      return;
    }

    const sortState: MatSortable = {
      id: fieldName,
      start: 'desc',
      disableClear: true
    };
    this.sort.sort(sortState);
  }