Skip to content

Commit 539ed14

Browse files
committed
feat(sort) add example of sorting programmatically
1 parent 60bf81b commit 539ed14

File tree

3 files changed

+44
-2
lines changed

3 files changed

+44
-2
lines changed

src/material-examples/table-sorting/table-sorting-example.css

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,7 @@ table {
55
th.mat-sort-header-sorted {
66
color: black;
77
}
8+
9+
.mat-form-field {
10+
margin: 16px 8px;
11+
}

src/material-examples/table-sorting/table-sorting-example.html

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,27 @@
1-
<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
1+
<mat-form-field>
2+
<mat-select [(ngModel)]="sortActive" placeholder="Active" (selectionChange)="sortTable()">
3+
<mat-option *ngFor="let option of displayedColumns" [value]="option">
4+
{{option}}
5+
</mat-option>
6+
</mat-select>
7+
</mat-form-field>
8+
9+
<mat-form-field>
10+
<mat-select [(ngModel)]="sortDirection" placeholder="Direction" (selectionChange)="sortTable()">
11+
<mat-option value="asc">
12+
asc
13+
</mat-option>
14+
<mat-option value="desc">
15+
desc
16+
</mat-option>
17+
</mat-select>
18+
</mat-form-field>
19+
20+
<table mat-table
21+
[dataSource]="dataSource"
22+
matSort matSortDisableClear [matSortActive]="sortActive" [matSortDirection]="sortDirection"
23+
(matSortChange)="handleSortChange($event)"
24+
class="mat-elevation-z8">
225

326
<!-- Position Column -->
427
<ng-container matColumnDef="position">

src/material-examples/table-sorting/table-sorting-example.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import {Component, OnInit, ViewChild} from '@angular/core';
2-
import {MatSort} from '@angular/material/sort';
2+
import {Sort, MatSort, MatSortable} from '@angular/material/sort';
33
import {MatTableDataSource} from '@angular/material/table';
44

55
export interface PeriodicElement {
@@ -31,6 +31,8 @@ const ELEMENT_DATA: PeriodicElement[] = [
3131
templateUrl: 'table-sorting-example.html',
3232
})
3333
export class TableSortingExample implements OnInit {
34+
sortActive = 'position';
35+
sortDirection = 'asc';
3436
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
3537
dataSource = new MatTableDataSource(ELEMENT_DATA);
3638

@@ -39,4 +41,17 @@ export class TableSortingExample implements OnInit {
3941
ngOnInit() {
4042
this.dataSource.sort = this.sort;
4143
}
44+
45+
sortTable(): void {
46+
this.sort.sort(<MatSortable>{
47+
id: this.sortActive,
48+
start: this.sortDirection,
49+
disableClear: true,
50+
});
51+
}
52+
53+
handleSortChange(sort: Sort): void {
54+
this.sortActive = sort.active;
55+
this.sortDirection = sort.direction;
56+
}
4257
}

0 commit comments

Comments
 (0)