【发布时间】:2021-08-30 11:48:57
【问题描述】:
我正在尝试使用 MatSort 模块在 Angular Material 中对我的表格进行排序,但出现此错误:
Property 'sort' has no initializer and is not definitely assigned in the constructor.
这是我的 ts 文件:
import { Component, OnInit, ViewChild } from '@angular/core';
import { Personal } from 'src/app/models/personal.model';
import { PersonalService } from 'src/app/services/personal.service';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatSort, MatSortModule, MatSortHeader } from '@angular/material/sort'
@Component({
selector: 'app-personal-list',
templateUrl: './personal-list.component.html',
styleUrls: ['./personal-list.component.css']
})
export class PersonalListComponent implements OnInit {
personals?: Personal[];
currentPersonal?: Personal;
currentIndex = -1;
name = '';
PERSONAL_DATA : Personal[] = []
displayedColumns: string[] = ['name', 'action'];
dataSource = new MatTableDataSource<Personal>(this.PERSONAL_DATA);
@ViewChild(MatSort) sort: MatSort;
constructor(private personalService: PersonalService) { }
ngOnInit(): void {
this.getAllPersonalTable();
}
private getAllPersonalTable(){
let resp = this.personalService.getAllPersonal();
resp.subscribe(report =>this.dataSource.data=report as Personal[]);
this.dataSource.sort = this.sort;
}
}
此行出现错误
@ViewChild(MatSort) sort: MatSort;
是的,我试过sort!。这消除了错误,但无法编译我的页面。 "strictPropertyInitialization": false,在 tsconfig.json 文件中也是如此。
非常感谢任何有关如何解决的帮助!!!
【问题讨论】:
-
不应该在 app.module 中导入模块 MatSortModule、MatPaginatorModule 吗?
-
@SanjayChoudhary 我有一个personal.module.ts 文件,我在其中导入了所有模块,我也在app.module.ts 文件中导入了这些模块
-
那你为什么在 app.component 文件中有这些模块呢?你应该检查 tsconfig 中所有说严格的属性。
-
@SanjayChoudhary 因为我必须在 app.module.ts 文件中导入 module.ts 文件。它基本上是共享模块-另外,我认为您混淆了 app.component 和 app.module 文件