The problem (Angular 14)
I want to override a function from a library Component (Angular Material) without re-implementing the whole component.
The idea
My thinking is inspired by one of the examples from MatPaginator
documentation.
They override the default implementation of the getRangeLabel
function from MatPaginatorIntl
and then they provide the new implementation in the Component using the providers
field:
@Injectable()
export class MyCustomPaginatorIntl implements MatPaginatorIntl {
getRangeLabel(page: number, pageSize: number, length: number): string {
if (length === 0) {
return $localize`Page 1 of 1`;
}
const amountPages = Math.ceil(length / pageSize);
return $localize`Page ${page + 1} of ${amountPages}`;
}
}
@Component({
providers: [{provide: MatPaginatorIntl, useClass: MyCustomPaginatorIntl}],
})
export class PaginatorIntlExample {}
Naturally I was wondering if I can do the same for the MatPaginator
Component itself:
@Injectable()
export class MyCustomPaginatorComponent extends MatPaginator {
override hasNextPage(): boolean {
return true;
}
}
@Component({
providers: [{provide: MatPaginator , useClass: MyCustomPaginatorComponent}],
})
export class PaginatorIntlExample {}
But this doesn’t work.
Similar topics
I understand that MatPaginatorIntl
is directly injected into MatPaginator
‘s constructor, while MatPaginator
is not Injectable
itself but rather a Component
. But I was wondering if there is any way to override a function from MatPaginator
without re-implementing the template.
I found a similar question but I want to extend the behaviour of MatPaginator
rather than re-implementing the whole new Component with the same selector.
In another post they are accessing MatPaginator
with ViewChild
but I want to avoid this approach because I will need this in a generic Component which most of the time uses default MatPaginator
but in a special case uses the custom implementation.
Probably the best solution would be to use content projection but then I would need to change all of the already existing components that use this generic component and since this is a special case it also doesn’t make a lot of sense.
TL;DR;
I want to override a function from MatPaginator
for just one module. How can I do that?