Home > Software design >  Populate Mat Table search fields from code
Populate Mat Table search fields from code

Time:09-21

I have a mat-table. How can I populate a <mat-header-cell> from code class.ts?

The second row consists of filter fields. And if I do a GET request behind the scene with some filters computed in class.ts I need to reflect those changes on the UI also.

For example
I have selected Sort descending on User column. This is saved into Local Storage in browser. I logout then I login and return to this table. In ngOnInit I retrieve from local storage and I send a GET request with User sorting activated. My data comes correctly but on frontend UI this arrow is not shown. This problem is also for input filters, second row.

The filters have <input> and I can give [defaultValue]. But the sort arrow I cannot access. In HTML its only:

<mat-table
    [dataSource]="tableDataSource"
    matSort
    (matSortChange)="sortTableData($event)">

Header and Filters

CodePudding user response:

if you see the API of MatSort you can see two properties: matSortActive and matSortDirection so you can use

In .ts declare two variables

sortActive:string="name"
sortDirection:SortDirection="asc"

In .html

<table mat-table [dataSource]="dataSource" matSort
                 (matSortChange)="announceSortChange($event)"
                  
                 [matSortActive]='sortActive'
                 [matSortDirection]='sortDirection' >

You can also get the matSort using ViewChild and use the method sort. Some like

  @ViewChild(MatSort) sort: MatSort;
  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
    this.sort.sort(
            {id:this.sortActive,
             start:this.sortDirection,
             disableClear:false})
  }
  • Related