【发布时间】:2018-06-04 12:41:26
【问题描述】:
我尝试在我的项目中在 mat-table 中实现 mat-sort。开始我的项目后,我看到“排序”图标,可以点击它,但我的结果中没有任何排序,总是相同的视图。
组件文件:
@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();
}
}
}
服务文件:
@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 文件:
<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>
还导入了所有必要的材料模块:MatSortModule, MatTabsModule。
我的步骤是:
1. 组件新增:@ViewChild(MatSort) sort: MatSort。
2.实现AfterViewInit。
3. 补充:
ngAfterViewInit() {
this.dataSource.sort = this.sort;
}
- 在html文件中添加:
<mat-table>中的matSort。 - 将 mat-sort-header 添加到
<mat-cell-header>。
就像我写的:我在列上看到排序图标,但点击后 - 没有任何变化,没有任何排序。
【问题讨论】:
-
你能为此创建一个 plunkr/jsfiddle 吗?
标签: html angular typescript material-design