I'm coding in Visual Studio Code
an Angular 8
project and just added some strict mode configuration:
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"noImplicitThis": true,
"alwaysStrict": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
Now, my paginator which was working fine, now is not even compiling.
I can instantiate the MatSort with:
@ViewChild(MatSort, { static: true }) sort: MatSort = new MatSort();
But I cannot do the same for the MatPaginator member variable:
@ViewChild(MatPaginator, { static: true }) paginator?: MatPaginator;
This forces me to add some checks in the code:
if (this.paginator) {
I read this blog article but I'm still searching for an alternative solution.
The paginator in the view:
<mat-paginator [pageIndex]="currentPageNumber" [length]="totalElements" [pageSize]="elementsPerPage" [pageSizeOptions]="pageSizeOptions" [showFirstLastButtons]="true"></mat-paginator>
It is not within an ngIf
directive.
When instantiate with new MatPaginator()
, the error message says:
Expected 2-3 arguments, but got 0.ts(2554)
As MatPaginator
has non optional arguments, you must initialize with the arguments. The first argument is a MapPaginatorIntl
class; and the second is a ChangeDetectorRef
abstract class, which is not possible to instantiate, but you can call ChangeDetectorRef.prototype
to get rid of the error message, like this:.
@ViewChild(MatPaginator) paginator: MatPaginator = new MatPaginator(new MatPaginatorIntl(), ChangeDetectorRef.prototype);
This will happen because of the STRICT mode enabled and if it is disabled then no issue there.
Тhis will be some of an answer but here is how the guys from angular have dealt with this issue, and for me, this is the way you should think about the stuff when using Strict mode. Just declare it also as UNDEFINED
paginator: MatPaginator | undefined;
and then wherever you are using it you will have to check for the existence of it.
if (this.paginator)
Since I had the same problem, I have checked in the GitHub repo for angular material schematics, see lin 44 and line 57 Link to file in github
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With