【问题标题】:Angular appliying filter to custom data sourceAngular 将过滤器应用于自定义数据源
【发布时间】:2021-04-06 20:03:18
【问题描述】:

我使用ng generate @angular/material:material-table --name <component-name> 命令创建了我的角度数据表。我遵循了一些关于如何使用 http 请求填充此数据表的教程。我也尝试对数据表应用一些过滤。

这是我的 op-dta-datasource.ts 文件代码。

export interface OpDataSecondItem {
  id: number;
  title:string;
  close_date:Date;
}
export class OpDataSecondDataSource extends DataSource<OpDataSecondItem> {
  data: OpDataSecondItem[];
  paginator: MatPaginator;
  sort: MatSort;

  constructor() {
    super();
  }
  connect(): Observable<OpDataSecondItem[]> {
    // Combine everything that affects the rendered data into one update
    // stream for the data-table to consume.
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    return merge(...dataMutations).pipe(map(() => {
      return this.getPagedData(this.getSortedData([...this.data]));
    }));
  }
......

这是我的 op-dta.component.ts

@Component({
  selector: 'op-data-second',
  templateUrl: './op-data-second.component.html',
  styleUrls: ['./op-data-second.component.css']
})
export class OpDataSecondComponent implements AfterViewInit, OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatTable) table: MatTable<OpDataSecondItem>;

  dataSource: OpDataSecondDataSource;
  searchKey: string;
  displayedColumns = ['id', 'title','close_date','published_date'];
  
  constructor(private service: HttpserviceService){}

  ngOnInit() {
    this.dataSource = new OpDataSecondDataSource();
     this.service.getOps('').subscribe((data:OpDataSecondItem[])=>{
       this.dataSource.data =  data;
     });
    
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    this.table.dataSource = this.dataSource;
  }


  onSearchClear() {
    this.searchKey = "";
    this.applyFilter();
  }

  applyFilter() {
    this.dataSource.data['title'].filter = this.searchKey.trim().toLowerCase();
  }
}

还有我的 html 代码。

<div class="search-div">
  <mat-form-field class="search-form-field" >
    <input matInput [(ngModel)]="searchKey" placeholder="Search" autocomplete="off" (keyup)="applyFilter()">
    <button mat-button matSuffix mat-icon-button aria-label="Clear"*ngIf="searchKey"  (click)="onSearchClear()">
      <mat-icon>close</mat-icon>
    </button>
  </mat-form-field>
</div>


<div class="mat-elevation-z8">
  <table   mat-table class="full-width-table" matSort aria-label="Elements">
    <!-- Id Column -->
    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef mat-sort-header><strong>Id</strong>   </th>
      <td mat-cell *matCellDef="let row"> <span>{{row.id}}</span></td>
    </ng-container>

   .............

  <mat-paginator #paginator
      [length]="dataSource?.data.length"
      [pageIndex]="0"
      [pageSize]="10"
      [pageSizeOptions]="[5, 10, 25, 50]"
      showFirstLastButtons>
  </mat-paginator>
</div>

我编写的过滤器方法不起作用,我看到一些代码他们正在使用我不理解的 mattabledatasource 并且我无法将我的代码转换为那种方式。任何人都可以帮助我如何编写有效的过滤方法,以及如何转换我的代码以便以我当前模块不会中断的方式使用 MatTableDataSource。

【问题讨论】:

    标签: angular filter datatable


    【解决方案1】:

    试试这个...

    ngOnInit() {
        this.dataSource = new MatTableDataSource();
        this.service.getOps('').subscribe((data: OpDataSecondItem[]) => {
            this.dataSource.data = data;
        });
    
        this.dataSource.filterPredicate = function (data, filter: string): boolean {
            return data.title.toLowerCase().includes(filter);
        };
    }
    
    applyFilter() {
        this.dataSource.filter = this.searchKey.trim().toLowerCase();;
      }
    

    【讨论】:

    • 它说,“OpDataSecondDataSource”类型上不存在属性“filterPredicate”
    • 现在我已经编辑了我的答案。请立即查看
    • 现在它说类型“MatTableDataSource”缺少类型“OpDataSecondDataSource”的以下属性:getPagedData、getSortedDatats(2739)
    • 更改这一行 -> dataSource: OpDataSecondDataSource 为 dataSource: any;
    【解决方案2】:
     <app-search [from]="searchFrom" [setSearchString]="searchString" (filterEvent)="applyFilter($event)"
              (reloadEvent)="refreshList($event)"></app-search>
    
    
      applyFilter(filterValue: string) {
        filterValue = filterValue.trim(); // Remove whitespace
        filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
        // this.configProdService.dataSource.filter = filterValue;
        this.comonService.setPageDetails({ offset: this.offset });
        const pagination: any = {
          offset: 0,
          limit: 10,
          filter: filterValue
        };
        this.getCampaignsList(pagination);
      }
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2019-10-01
      • 2015-04-26
      • 2012-01-12
      • 1970-01-01
      • 2016-12-26
      相关资源
      最近更新 更多