You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

子组件用Mat-Paginator控制父组件Mat-Table,出现0 of 0显示问题

解决子组件Mat-Paginator显示“0 of 0”并控制父组件Mat-Table分页的问题

你当前代码存在几个核心问题导致分页器异常:

  • 父组件错误地将dataSource声明为@Input(),它应该是组件内部初始化的数据源,而非接收外部输入
  • 父组件里的@ViewChild('paginator')找不到对应元素,因为分页器模板定义在子组件中
  • 父子组件重复给dataSource绑定分页器和排序,导致关联逻辑混乱
  • 子组件中输入的paginator参数和自身模板的#paginator重名,引发变量冲突

以下是修正后的完整代码:

父组件代码

parent.html

<table mat-table [dataSource]="dataSource">
  <!-- 你的列定义 -->
  ...columns...
</table>
<app-child [tableDataSource]="dataSource" [tableSort]="sort"></app-child>

parent.ts

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html'
})
export class ParentComponent implements AfterViewInit {
  // 内部初始化数据源,替换成你的实际数据数组
  dataSource = new MatTableDataSource<any>([]);
  @ViewChild(MatSort) sort!: MatSort;

  ngAfterViewInit(): void {
    // 给数据源绑定排序组件
    this.dataSource.sort = this.sort;
  }
}

子组件代码

child.ts

import { Component, Input, AfterViewInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';

@Component({
  selector: 'app-child',
  template: `
    <mat-paginator #childPaginator [pageSizeOptions]="[10, 20, 50, 100]"></mat-paginator>
  `
})
export class ChildComponent implements AfterViewInit {
  @Input() tableDataSource!: MatTableDataSource<any>;
  @Input() tableSort!: MatSort;
  // 获取子组件自身的分页器实例
  @ViewChild('childPaginator') childPaginator!: MatPaginator;

  ngAfterViewInit(): void {
    // 将子组件的分页器绑定到父组件传入的数据源
    this.tableDataSource.paginator = this.childPaginator;
    // 确保排序组件正确绑定(如果父组件未完成绑定)
    if (this.tableSort) {
      this.tableDataSource.sort = this.tableSort;
    }
  }
}

额外注意事项

  • 确保初始化dataSource时传入了有效的数据数组,空数组会导致分页器显示“0 of 0”
  • 移除父组件中的ngAfterContentChecked和手动变更检测逻辑,Angular默认变更检测足以处理此场景
  • 如果数据是异步加载的(比如从API获取),需要在数据加载完成后重新设置dataSource.data,或者使用BehaviorSubject配合AsyncPipe

内容的提问来源于stack exchange,提问作者aroundme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 01:43:11