Skip to content

Commit 25720a6

Browse files
committed
feat(sort) add example of sorting programmatically
1 parent d72e8ea commit 25720a6

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 [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, MatTableDataSource} from '@angular/material';
2+
import {Sort, MatSort, MatSortable, MatTableDataSource} from '@angular/material';
33

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

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

0 commit comments

Comments
 (0)