I want to change the texts by icons, what do I have to do to change the texts by icons ?
I have to find the result like this :
file.ts:
ngAfterViewInit() {
this.current.paginator = this.paginator;
const lastBtn = this.el.nativeElement.querySelector(
'.mat-paginator-navigation-last'
);
if (lastBtn) {
lastBtn.innerHTML = 'Last';
}
const firstBtn = this.el.nativeElement.querySelector(
'.mat-paginator-navigation-first'
);
if (firstBtn) {
firstBtn.innerHTML = 'First';
}
}
If you want to change the button icons, it is possible to do so.\
In order to do so, we need to alter the html that is being generated by the
mat-paginator
.The following directive does it:
Now onto the why.
Directive
: we create our attribute directive that will adjust the icons of theMatPaginator
. Attribute Directives are recommended when we only want to edit the html of something.AfterViewInit
: we can only edit the contents of theMatPaginator
html after it has been fully initialise. The AfterViewInit lifecycle hook is the best hook for the task.ElementRef
: this provides access to the HTML code that our directive is placed on.Renderer2
: the recommended utility to modify HTML elements safely. It is the basis that directives likengStyle
andngClass
use being the scenes. We can achieve the same goal by directly editing the DOM elements, however, this may raise errors if we edit it incorrectly.setFirstIcon
,setPreviousIcon
,setNextIcon
,setLasttIcon
: these are very similar methods, they search for the button that needs to be updated and if it exists, they call thereplaceSvgWithIcon
method to perform the actual changes. Only exception to this is thesetPreviousIcon
method since there is no icon that matches what you want. To achieve the look you want, I rotate the next icon.replaceSvgWithIcon
: starts by removing the<svg>...</svg>
tag from the button. This is the tag that contains the actual image for the icon, the remaining HTML in the button element is for other things like the ripple. Once the element has been removed, we create a newHTMLSpanElement
. It is on this element that we will set thematerial-icons
class (so that it uses the Material Icons), and the value of the icon. After this is done, we append it to the provided button and return it (we return the element in case we want to modify something else that is not generic).To use this directive, we simply call on the html selector of the paginator:
The above case is meant for Angular 15. For previous versions, simple remove the '-mdc' from the selectors, like so:
'.mat-mdc-paginator-navigation-first'
to `'.mat-paginator-navigation-first';'.mat-mdc-paginator-navigation-previous'
to'.mat-paginator-navigation-previous'
;'.mat-mdc-paginator-navigation-next'
to'.mat-paginator-navigation-next'
;'.mat-mdc-paginator-navigation-last'
to'.mat-paginator-navigation-last'
;