Angular 18:MatPaginatorIntl用作MatTableDataSource分页器报错问询
Angular Material自定义分页器标签后无法绑定数据源的问题
问题场景
使用Angular Material 18.2.8,自定义了继承自MatPaginatorIntl的国际化标签类:
import { Injectable } from "@angular/core"; import { MatPaginatorIntl } from "@angular/material/paginator"; import { Subject } from "rxjs"; @Injectable({ providedIn: 'root' }) export default class CustomPaginatorIntl extends MatPaginatorIntl { override changes = new Subject<void>(); constructor() { super(); } override firstPageLabel = `WASDASD1`; override itemsPerPageLabel = `WASDASD1 per page:`; override lastPageLabel = `Last WASDASD1`; override nextPageLabel = 'WASDASD1 page'; override previousPageLabel = 'WASDASD1 page'; override getRangeLabel = (page: number, pageSize: number, length: number) => { return "WASD"; } }
并在表格组件中提供该类:
@Component({ selector: 'app-notes-table', standalone: true, imports: [MatDividerModule, MatTableModule, MatPaginatorModule, MatCheckboxModule, MatProgressSpinnerModule], templateUrl: './notes-table.component.html', styleUrl: './notes-table.component.css', providers: [{ provide: MatPaginatorIntl, useClass: CustomPaginatorIntl }] })
尝试将MatPaginatorIntl实例绑定到MatTableDataSource的分页器时出现类型错误:
TS2740: Type 'MatPaginatorIntl' is missing the following properties from type 'MatPaginator': _intl, _changeDetectorRef, _pageSizeLabelId, _intlChanges, and 32 more.
错误原因
MatPaginatorIntl是负责提供分页器文本标签的国际化服务类,而MatTableDataSource的paginator属性需要的是**MatPaginator组件实例**(对应页面上的<mat-paginator>元素)。两者是完全不同的类型,直接绑定必然导致类型不匹配。
解决方案
在模板中添加
<mat-paginator>组件
确保页面上存在分页器组件:<mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>获取
MatPaginator组件实例而非MatPaginatorIntl
修改组件类中的@ViewChild和初始化逻辑:import { MatPaginator } from '@angular/material/paginator'; // ... notes: MatTableDataSource<Note> = new MatTableDataSource<Note>(); @ViewChild(MatPaginator) paginator!: MatPaginator; ngAfterViewInit(): void { this.notes.paginator = this.paginator; }自定义标签自动生效
你已经通过组件的providers配置了自定义的MatPaginatorIntl,MatPaginator组件会自动注入并使用该服务的文本标签,无需额外绑定操作,页面上的分页器会直接显示你自定义的内容。
内容的提问来源于stack exchange,提问作者rzdrrw
相关产品推荐
相关产品推荐

