我正在Visual Studio Code一个Angular 8项目中编码,只是添加了一些严格模式配置:
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"noImplicitThis": true,
"alwaysStrict": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
Run Code Online (Sandbox Code Playgroud)
现在,我的分页器工作正常,现在甚至没有编译。
我可以使用以下命令实例化 MatSort:
@ViewChild(MatSort, { static: true }) sort: MatSort = new MatSort();
Run Code Online (Sandbox Code Playgroud)
但是我不能对 MatPaginator 成员变量做同样的事情:
@ViewChild(MatPaginator, { static: true }) paginator?: MatPaginator;
Run Code Online (Sandbox Code Playgroud)
这迫使我在代码中添加一些检查:
if (this.paginator) {
Run Code Online (Sandbox Code Playgroud)
我阅读了这篇博客文章,但我仍在寻找替代解决方案。
视图中的分页器:
<mat-paginator [pageIndex]="currentPageNumber" [length]="totalElements" [pageSize]="elementsPerPage" [pageSizeOptions]="pageSizeOptions" [showFirstLastButtons]="true"></mat-paginator>
Run Code Online (Sandbox Code Playgroud)
它不在ngIf指令内。
使用 实例化时new MatPaginator(),错误消息说:
预期 2-3 个参数,但得到 0.ts(2554)
与MatPaginator非可选参数一样,您必须使用参数进行初始化。第一个参数是一个MapPaginatorIntl类;第二个是ChangeDetectorRef抽象类,不能实例化,但是可以调用ChangeDetectorRef.prototype去掉错误信息,像这样:。
@ViewChild(MatPaginator) paginator: MatPaginator = new MatPaginator(new MatPaginatorIntl(), ChangeDetectorRef.prototype);
Run Code Online (Sandbox Code Playgroud)
发生这种情况是因为启用了 STRICT 模式,如果禁用它则没有问题。
\n\xd0\xa2his 将是一些答案,但这是来自 Angular 的人如何处理这个问题的,对我来说,这就是使用严格模式时应该考虑的方式。只需将其声明为UNDEFINED
\npaginator: MatPaginator | undefined;\nRun Code Online (Sandbox Code Playgroud)\n然后无论你在哪里使用它,你都必须检查它是否存在。
\nif (this.paginator)\nRun Code Online (Sandbox Code Playgroud)\n由于我遇到了同样的问题,我已在 GitHub 存储库中检查了角度材料原理图,请参阅第 44 行和第 57 行\n链接到 github 中的文件
\n在 的情况下MatPaginator,您还没有实例化,只是在那里声明。MatSort为了避免该检查,如果您的要求满足,则必须像示例中那样实例化。
@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator = new MatPaginator();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1584 次 |
| 最近记录: |