How do we sort or Alphabetize by Last Name using angular mat table?

Viewed 169

#right now this is the data being displayed , want I want is that to sort it or Alphabetize by Last Name so it it would be alphabetize by last name then Alexa Bermudes should be on top of Al geizer.

How do we do it on a datasource ? right now I am using mat table. Any idea would be muchly appreaciated. Thank you.

#sample data

[
    {
        "id": 7,
        "fullName": "Al Geizer",
        "roleDisplay": null,
        "firstName": "Al",
        "lastName": "Geizer",
        "emailAddress": "dasdasd@gmai..com",
        "phoneNumber": null,
        "companyName": null,
        "title": null,
        "lastLogin": null,
        "createdDate": "09/06/2021 3:00:24 pm",
        "isVerified": null,
        "roleDto": null,
        "status": "Active",
        "securityRole": "Broker",
        "lastLoggedIn": "",
        "teamCount": 8,
        "transactionRoleList": null
    },
    {
        "id": 1,
        "fullName": "Alexa Bermudes",
        "roleDisplay": null,
        "firstName": "Alexa",
        "lastName": "Bermudes",
        "emailAddress": "aadasda@gmail.com",
        "phoneNumber": "3",
        "companyName": "ARMermwood",
        "title": "COO",
        "lastLogin": null,
        "createdDate": "10/08/2021 2:06:02 am",
        "isVerified": null,
        "roleDto": null,
        "status": "Active",
        "securityRole": "Transaction Super User",
        "lastLoggedIn": "",
        "teamCount": 14,
        "transactionRoleList": null
    },
  
]

enter image description here

#HTML CODE

<mat-table [dataSource]="userTable.dataSource" [@animateStagger]="{value:'50'}" matMultiSort
                          (matSortChange)="userTable.onSortEvent()">
                          <ng-container matColumnDef="fullName">
                            <mat-header-cell *matHeaderCellDef fxHide fxShow.gt-xs fxLayoutAlign="start center"
                              mat-multi-sort-header="fullName" class="users-table-header">
                              Full Name
                            </mat-header-cell>
                            <mat-cell *matCellDef="let item" fxHide fxShow.gt-xs fxShow.gt-md
                              [matTooltip]="item.fullName" fxLayoutAlign="start center">
                              <app-user-profile-icon [firstName]="item.firstName" [lastName]="item.lastName" [size]="32"
                                style="padding-right: 8px;">
                              </app-user-profile-icon>
                              {{ item.firstName }} {{ item.lastName }}
                            </mat-cell>
                          </ng-container>

TS CODE

  constructor(
    private _userService: UserService,
    private _notificationService: NotificationService,
    private _teamService: TeamService,
    private router: Router,
    private _formBuilder: FormBuilder,    
    private route: ActivatedRoute,
  ) {

    this.selectedTabIndex = this.route.snapshot.paramMap.get('tab');

    this.userTable = new TableData<UsersDto>(
      [
        { id: 'fullName', name: 'Full Name' },
      ], { defaultSortParams: ['fullName'], defaultSortDirs: ['asc'] }
    );

    this.userTable.pageSize = 10;
    this.userTable.pageIndex = 0;
  }

ngOnInit(): void {
    this.currentTab = 0;
    this.userTable.dataSource = new MatMultiSortTableDataSource(this.sort, this.CLIENT_SIDE);
    this.userTable.nextObservable.subscribe(() => { this._tableEvent(); });
    this.userTable.sortObservable.subscribe(() => { this._tableEvent(); });
    this.userTable.previousObservable.subscribe(() => { this._tableEvent(); });
    this.userTable.sizeObservable.subscribe(() => { this._tableEvent(); });
    this._getPageCount();
  }


  private _tableEvent() {
    if (this.filterFormControl.get('filters').value === '1') {
      this._pageEventMyList();
    }
  private _pageEventMyList() {
    this.isLoading = true;
    this.userTable.data = [];
    this._userService.getAllUsers(
      this.accountId,
      this.userTable.pageIndex + 1,
      this.userTable.pageSize,
      this.searchInput.nativeElement.value,
      this.userTable.sortParams,
      this.userTable.sortDirs
    )
      .pipe(
        finalize(() => this.isLoading = false)
      )
      .subscribe({
        error: err => this._notificationService.showError(err),
        next: res => {
          this.userTable.totalElements = res.totalItemCount;
          this.totalData = res.totalItemCount;
          this.currentDisplayedData = res.lastItemOnPage;
          console.log("users" , res.items)
          this.userTable.data = res.items as UsersDto[];
        },
        complete: noop
      });
  }

------------ Logic does not work on this one .

#data2


 this.dataSource.data =  [
        {
            "id": 86,
            "fullName": "Sake  Meme",
            "roleDisplay": null,
            "firstName": "Sake ",
            "lastName": "Meme",
            "emailAddress": "sakem89643@100xbit.com",
            "phoneNumber": "2210495",
            "companyName": "ABC",
            "title": "CEO",
            "lastLogin": null,
            "createdDate": "10/08/2021 12:42:09 pm",
            "isVerified": null,
            "roleDto": null,
            "status": "Active",
            "securityRole": "Broker",
            "lastLoggedIn": "",
            "teamCount": 0,
            "transactionRoleList": null
        },
        {
            "id": 10090,
            "fullName": "ADASDAD@gmail.com ADASDAD@gmail.com",
            "roleDisplay": null,
            "firstName": "ADASDAD@gmail.com",
            "lastName": "ADASDAD@gmail.com",
            "emailAddress": "ADASDAD@gmail.com",
            "phoneNumber": null,
            "companyName": "ADASDAD@gmail.com",
            "title": null,
            "lastLogin": null,
            "createdDate": "12/08/2021 6:41:02 am",
            "isVerified": false,
            "roleDto": null,
            "status": "Active",
            "securityRole": "Broker",
            "lastLoggedIn": "",
            "teamCount": 6,
            "transactionRoleList": null
        },
        {
            "id": 10089,
            "fullName": "AEasdasdasd@Test.com AEasdasdasd@Test.com",
            "roleDisplay": null,
            "firstName": "AEasdasdasd@Test.com",
            "lastName": "AEasdasdasd@Test.com",
            "emailAddress": "AEasdasdasd@Test.com",
            "phoneNumber": null,
            "companyName": "AEasdasdasd@Test.com",
            "title": null,
            "lastLogin": null,
            "createdDate": "12/08/2021 6:39:11 am",
            "isVerified": false,
            "roleDto": null,
            "status": "Invited",
            "securityRole": "Transaction Manager",
            "lastLoggedIn": "",
            "teamCount": 1,
            "transactionRoleList": null
        },
        {
            "id": 85,
            "fullName": "Roberto Barrion",
            "roleDisplay": null,
            "firstName": "Roberto",
            "lastName": "Barrion",
            "emailAddress": "abermud2@yahoo.com",
            "phoneNumber": "5551122",
            "companyName": "Company ABC",
            "title": "Intern",
            "lastLogin": null,
            "createdDate": "10/08/2021 1:42:57 am",
            "isVerified": true,
            "roleDto": null,
            "status": "Accepted",
            "securityRole": "Transaction Super User",
            "lastLoggedIn": "",
            "teamCount": 0,
            "transactionRoleList": null
        },
        {
            "id": 1,
            "fullName": "Alexa Bermudes",
            "roleDisplay": null,
            "firstName": "Alexa",
            "lastName": "Bermudes",
            "emailAddress": "aASDASD@gmail.com",
            "phoneNumber": "3",
            "companyName": "Xermwood",
            "title": "COO",
            "lastLogin": null,
            "createdDate": "10/08/2021 2:06:02 am",
            "isVerified": null,
            "roleDto": null,
            "status": "Active",
            "securityRole": "Transaction Super User",
            "lastLoggedIn": "",
            "teamCount": 14,
            "transactionRoleList": null
        },
    ]

#code 2

  private _transactionUserPageEvent() {
    this.isTransactionUserLoading = true;
    this._userProfileService.getUserProfileTableDropdownUnfiltered(this.accountId)
      .pipe(
        finalize(() => this.isTransactionUserLoading = false)
      )
      .subscribe({
        error: err => this._notificationService.showError(err),
        next: res => {
          // this._findSelectedUserWithRoles(this.selectedTransactionUser);
          let users = res;
          users.sort((a,b) => a.fullName.split(" ")[1] > b.fullName.split(" ")[1] ? 1: -1);
          console.log("users" , users)
          this.dataSource.data = users;
          this.totalData = res.length;
        },
        complete: noop
      });
  }
2 Answers

If you're using mat-table you can simply add MatSortModule that will helps. using MatSortModule you can sort by ascending order and descending order.

app.module.ts

You will have to import the MatSortModule.

more details

I assume that fullName will always contain both, firstName & lastName, So by just keep this in mind I have write down this simple script for you! hopefully it will help you

let data = [
    {
        "id": 7,
        "fullName": "Al Geizer",
        "roleDisplay": null,
        "firstName": "Al",
        "lastName": "Geizer",
        "emailAddress": "dasdasd@gmai..com",
        "phoneNumber": null,
        "companyName": null,
        "title": null,
        "lastLogin": null,
        "createdDate": "09/06/2021 3:00:24 pm",
        "isVerified": null,
        "roleDto": null,
        "status": "Active",
        "securityRole": "Broker",
        "lastLoggedIn": "",
        "teamCount": 8,
        "transactionRoleList": null
    },
    {
        "id": 1,
        "fullName": "Alexa Bermudes",
        "roleDisplay": null,
        "firstName": "Alexa",
        "lastName": "Bermudes",
        "emailAddress": "aadasda@gmail.com",
        "phoneNumber": "3",
        "companyName": "ARMermwood",
        "title": "COO",
        "lastLogin": null,
        "createdDate": "10/08/2021 2:06:02 am",
        "isVerified": null,
        "roleDto": null,
        "status": "Active",
        "securityRole": "Transaction Super User",
        "lastLoggedIn": "",
        "teamCount": 14,
        "transactionRoleList": null
    },
];

console.log(data); // Current Data

data.sort((a,b) => a.fullName.split(" ")[1] > b.fullName.split(" ")[1] ? 1: -1);

console.log(data); // Data after sort

private _pageEventMyList() {
    this.isLoading = true;
    this.userTable.data = [];

    this._userService.getAllUsers(
      this.accountId,
      this.userTable.pageIndex + 1,
      this.userTable.pageSize,
      this.searchInput.nativeElement.value,
      this.userTable.sortParams,
      this.userTable.sortDirs
    )
      .pipe(
        finalize(() => this.isLoading = false)
      )
      .subscribe({
        error: err => this._notificationService.showError(err),
        next: res => {
          this.userTable.totalElements = res.totalItemCount;
          this.totalData = res.totalItemCount;
          this.currentDisplayedData = res.lastItemOnPage;
          console.log("users" , res.items);

          
          let data = res.items as UsersDto[];
          data.sort((a,b) => a.fullName.split(" ")[1] > b.fullName.split(" ")[1] ? 1: -1);

          this.userTable.data = data;
        },
        complete: noop
      });
  }

Related