I tried to implement mat-sort in mat-table, in my project. After starting my project, I see "sort" icon, can click on it, but nothing sorting in my result, always that same view.
component-file:
@Component({
selector: 'app-test-component',
templateUrl: './testComponent.component.html',
styleUrls: ['./testComponent.component.css'],
providers: [TestService],
})
export class TestComponent implements OnInit, OnDestroy, AfterViewInit {
displayedColumns = ['Column1'];
dataSource = new MatTableDataSource<UserModel>();
private exDisplayNames: Subscription;
@ViewChild(MatSort) sort: MatSort;
constructor(private testService: TestService) { }
ngOnInit() {
this.exDisplayNames = this.testService.userNamesChanged.subscribe((userNameData: UserModel[]) => {
this.dataSource.data = userNameData;
});
this.testService.fetchUserName();
}
ngAfterViewInit() {
this.dataSource.sort = this.sort;
}
ngOnDestroy() {
if (this.exDisplayNames) {
this.exDisplayNames.unsubscribe();
}
}
}
service file:
@Injectable()
export class TestService {
userNamesChanged = new Subject<UserModel[]>();
private availableUserName: UserModel[] = [];
private fbSubs: Subscription[] = [];
constructor(private db: AngularFirestore) { }
fetchUserName() {
this.fbSubs.push(this.db.collection('names/')
.snapshotChanges()
.map(docArray => {
return docArray.map(doc => {
return {
displayUserName: doc.payload.doc.data().nick,
};
});
})
.subscribe((userData: UserModel[]) => {
this.availableUserName = userData;
this.userNamesChanged.next([...this.availableUserName]);
}, error => {
console.log(error);
}));
}
}
html file:
<section fxLayoutAlign="center">
<mat-card>
<mat-card-content>
<mat-table [dataSource]="dataSource" matSort>
<ng-container matColumnDef="Column1">
<mat-header-cell *matHeaderCellDef mat-sort-header>Nick</mat-header-cell>
<mat-cell fxLayout="row" fxLayoutAlign="center center" *matCellDef="let element">{{ element.displayUserName}}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
</mat-card-content>
</mat-card>
</section>
Also was imported all necessary material modules: MatSortModule, MatTabsModule
.
My steps are:
1. Added in component: @ViewChild(MatSort) sort: MatSort
.
2. Implements AfterViewInit.
3. Added:
ngAfterViewInit() {
this.dataSource.sort = this.sort;
}
- In html file added: matSort in
<mat-table>
. - Added mat-sort-header to
<mat-cell-header>
.
Like I wrote: I see sort icon on the column, but after clicking - nothing changing, nothing sorting.