Angular初学者:如何使用MatSortHeaderIntl的sortDescriptionLabel属性
如何使用Angular Material的MatSortHeaderIntl服务及sortDescriptionLabel属性
嘿,作为Angular Material的初学者,能注意到MatSortHeaderIntl这个服务说明你观察得很细致!这个服务的核心作用是帮你自定义排序表头的无障碍描述文本(比如给屏幕阅读器用的提示),也能用来调整排序状态的显示文案,其中sortDescriptionLabel就是控制排序状态描述的关键属性。
下面我给你一步步拆解具体用法:
1. 自定义MatSortHeaderIntl服务类
首先我们需要创建一个继承自MatSortHeaderIntl的自定义类,重写sortDescriptionLabel方法来定义我们自己的文案:
import { Injectable } from '@angular/core'; import { MatSortHeaderIntl } from '@angular/material/sort'; @Injectable() export class CustomSortIntl extends MatSortHeaderIntl { // 重写排序描述标签方法 override sortDescriptionLabel = (sortId: string, direction: 'asc' | 'desc') => { // sortId是你在mat-sort-header上设置的字段标识,direction是当前排序方向 switch (direction) { case 'asc': return `已按【${sortId}】升序排列`; case 'desc': return `已按【${sortId}】降序排列`; default: return ''; } }; }
这个方法会在用户切换排序状态时被调用,返回的字符串会作为屏幕阅读器的朗读内容,也可以配合tooltip组件显示给普通用户。
2. 替换默认的MatSortHeaderIntl服务
接下来我们需要在模块(或组件)的providers里注册自定义服务,替换掉Angular Material提供的默认服务:
全局生效(在模块中配置)
import { NgModule } from '@angular/core'; import { MatSortModule, MatSortHeaderIntl } from '@angular/material/sort'; import { CustomSortIntl } from './custom-sort-intl.service'; @NgModule({ imports: [MatSortModule], providers: [ // 用自定义类替换默认服务 { provide: MatSortHeaderIntl, useClass: CustomSortIntl } ] }) export class AppModule { }
仅当前组件生效
如果只需要在某个组件里使用自定义文案,直接在组件的providers数组里配置即可:
import { Component } from '@angular/core'; import { MatSortHeaderIntl } from '@angular/material/sort'; import { CustomSortIntl } from './custom-sort-intl.service'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', providers: [ { provide: MatSortHeaderIntl, useClass: CustomSortIntl } ] }) export class YourComponent { }
3. 正常使用排序表头组件
最后在模板里按照常规方式使用mat-sort和mat-sort-header就可以了,自定义的文案会自动生效:
<table matSort> <thead> <tr> <!-- mat-sort-header的值就是会传入sortDescriptionLabel的sortId --> <th mat-sort-header="userName">用户名</th> <th mat-sort-header="createTime">创建时间</th> </tr> </thead> <tbody> <!-- 表格数据行 --> </tbody> </table>
当你点击“用户名”表头切换到升序时,屏幕阅读器会朗读“已按【userName】升序排列”,完美实现自定义的排序提示文案!
内容的提问来源于stack exchange,提问作者vivek gupta
相关产品推荐
相关产品推荐

