首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用反应型阵列分选角材料表

用反应型阵列分选角材料表
EN

Stack Overflow用户
提问于 2020-11-21 20:29:47
回答 3查看 5K关注 0票数 2

以formArray为输入数据源,实现了对角料表的排序/过滤。

StackBlits码链

代码语言:javascript
复制
dataSource = new MatTableDataSource([]);
<table mat-table [dataSource]="formdataarray.controls" multiTemplateDataRows class="mat elevation-z8" matSort >
<ng-container  matColumnDef="{{column}}" *ngFor="let column of columnsToDisplay" >
<th mat-header-cell *matHeaderCellDef mat-sort-header>{{column}}</th>
<td mat-cell *matCellDef="let element"> {{ element.value[column] }}  </td>
</ng-container>

但是排序/过滤不起作用。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-11-22 05:38:51

你在这里有两个选择:

  • 使用普通数组formdataarray.controls作为dataSource,并实现所有DataSource方法,如filter,按您自己的排序。或者编写自定义CDK DataSource实现。另见https://blog.angular-university.io/angular-material-data-table/
  • 使用MatTableDataSource和调整过滤和排序逻辑来支持AbstractControl对象。

html

代码语言:javascript
复制
<table mat-table [dataSource]="dataSource"

ts

代码语言:javascript
复制
ngOnInit() {
  // fill FormArray
  ...
  this.dataSource.data = this.formdataarray.controls;
  this.dataSource.sortingDataAccessor = (data: AbstractControl, sortHeaderId: string) => {
    const value: any = data.value[sortHeaderId];
    return typeof value === 'string' ? value.toLowerCase() : value;
  };

  const filterPredicate = this.dataSource.filterPredicate;
  this.dataSource.filterPredicate = (data: AbstractControl, filter) => {
    return filterPredicate.call(this.dataSource, data.value, filter);
  }
}

叉式斯塔克布利茨

此外,如果要向FormArray添加新项,也应该更新this.dataSource.data。另见使用FormArray的角材料可编辑表

票数 5
EN

Stack Overflow用户

发布于 2020-11-21 21:46:17

您还需要添加事件(matSortChange)=sortTable($event)

table标记

并在组件中添加sortTable逻辑。

票数 0
EN

Stack Overflow用户

发布于 2022-02-24 20:41:18

需要ngAfterViewInit才能工作

代码语言:javascript
复制
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';

...

@ViewChild(MatSort, {static: false}) sort: MatSort

...

ngOnInit() {
  this.getYourData$.subscribe(d => this.data = new MatTableDataSource(d));
}

ngAfterViewInit(): void {

  this.data.sortingDataAccessor = (data: AbstractControl, sortHeaderId: string) => {
  const value: any = data.value[sortHeaderId];
  return typeof value === 'string' ? value.toLowerCase() : value;
};

this.data.sort = this.sort; // where this.sort defined above.

  this.data.filterPredicate = (data: AbstractControl, filter) => {
  // return true or false on data.
  }
}


... html

<table matSort ...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64947763

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档