Issue
Code that I'm testing is here: Test code - Stackblitz
I'm using an extended MatPaginatorIntl class to customize its labels. It works, but I would like to set a custom variable (called someProperty in this code example):
import { MatPaginatorIntl } from '@angular/material/paginator';
import { Injectable } from '@angular/core';
@Injectable()
export class CustomMatPaginatorIntl extends MatPaginatorIntl {
public someProperty: number;
constructor() {
super();
this.getAndInitTranslations();
}
setSomeProperty(value:number)
{
this.someProperty = value;
}
getAndInitTranslations() {
this.itemsPerPageLabel = "Items per page";
this.nextPageLabel = "Next";
this.previousPageLabel = "Previous";
this.changes.next();
}
override getRangeLabel = (page: number, pageSize: number, length: number) => {
return `${this.someProperty}`; // use someProperty here
}
}
In the paginator-configurable-example.ts, I would like to set that variable (e.g. in OnInit), but the following approach is not working (sorry if it is completely wrong):
export class PaginatorConfigurableExample implements OnInit{
@ViewChild(MatPaginatorIntl) pag: MatPaginatorIntl;
// MatPaginator Inputs
length = 100;
pageSize = 10;
pageSizeOptions: number[] = [5, 10, 25, 100];
// MatPaginator Output
pageEvent: PageEvent;
setPageSizeOptions(setPageSizeOptionsInput: string) {
this.pageSizeOptions = setPageSizeOptionsInput.split(',').map(str => +str);
}
ngOnInit(): void {
// SET MatPaginatorIntl variable
this.pag.setSomeProperty(100);
}
}
How could I access the custom variable from the PaginatorConfigurableExample code?
Solution
@ViewChild
works only for classes that are decorated with @Component
/ @Directive
Angular ViewChild Documentation
So here is the solution:
- Add @Directive decorator to
CustomMatPaginatorIntl
instead of @Injectable.
@Directive({ selector: 'mat-paginator' })
export class CustomMatPaginatorIntl extends MatPaginatorIntl {
...
}
- In
main.ts
; removeCustomMatPaginatorIntl
fromproviders
and add it todeclarations
.
declarations: [CustomMatPaginatorIntl, PaginatorConfigurableExample],
- In the
paginator-configurable-example.ts
, change theViewChild
type fromMatPaginatorIntl
toCustomMatPaginatorIntl
@ViewChild(CustomMatPaginatorIntl) pag: CustomMatPaginatorIntl;
Forked working example: https://stackblitz.com/edit/angular-vqbvpq-lj8xmi?file=app/paginator-configurable-example.ts
Answered By - Zeeshan S.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.