【问题标题】:angular 7 material table - filter is not working properlyangular 7 材料表 - 过滤器无法正常工作
【发布时间】:2020-01-22 00:19:04
【问题描述】:

我创建了一个页面,其中显示了角度材料表数据。在表格数据之上,我放置了一个过滤器输入,以过滤格式显示数据。一切正常,但我观察到一种奇怪且出乎意料的角度行为。对于某些字符,它会在每次击键时显示过滤的行,但对于其他一些字符,它不会在击键时显示行。

listusers.component.html

 <div class="example-container mat-elevation-z8">

  <mat-form-field>
    <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter" autocomplete="off">
  </mat-form-field>

  <table mat-table [dataSource]="dataSource">

    <ng-container matColumnDef="position">
      <th mat-header-cell *matHeaderCellDef> No. </th>
      <td mat-cell *matCellDef="let element"> {{element.index}} </td>
    </ng-container>

    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> Name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>

    <ng-container matColumnDef="gender">
      <th mat-header-cell *matHeaderCellDef> Gender </th>
      <td mat-cell *matCellDef="let element"> {{element.gender}} </td>
    </ng-container>

    <ng-container matColumnDef="score">
      <th mat-header-cell *matHeaderCellDef> Score </th>
      <td mat-cell *matCellDef="let element"> {{element.score}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns; let i = index" 
    ></tr>
  </table>
</div>

listusers.component.ts

import { Component, OnInit } from '@angular/core';
import { ListService } from '../services/list.service';
import { User } from '../model/user.model';
import { MatTableDataSource } from '@angular/material';
import { FormControl } from '@angular/forms';


@Component({
  selector: 'listusers',
  templateUrl: './listusers.component.html',
  styleUrls: ['./listusers.component.css']
})
export class ListusersComponent implements OnInit {
  public users: User[] = [];
  displayedColumns = [ 'position','name', 'gender', 'score'];
  dataSource: MatTableDataSource<User>; 

  constructor(private listsrv:ListService) { }

  ngOnInit() {      
    this.loaddata();

    if(this.dataSource){
      this.dataSource.filterPredicate = (data: User, filtersJson: string) => {
        const matchFilter = [];
        const filters = JSON.parse(filtersJson);

        filters.forEach(filter => {
          const val = data[filter.id] == null ? '' : data[filter.id];
          matchFilter.push(val.toLowerCase().includes(filter.value.toLowerCase()));
        });
          return matchFilter.every(Boolean);
      };
    }
  }

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
    this.dataSource.filter = filterValue;
    console.log('filterValue',filterValue)
  }

  loaddata(){
    this.listsrv.getList()
    .subscribe(
      result => { 
        for(var key in result){ 
            this.users.push(result[key])
        } 
      },
      error => {console.log(' error',error)},
      () => {console.log(this.users)
        this.dataSource = new MatTableDataSource(this.users);        
      }
    ) 
  }
}

一些 CSS 也存在,但不共享,因为它可以减少问题的长度。我正在使用的数据来自 http 服务调用

getList(){return this.http.get(this.url+'/list');}

这实际上是在服务器上调用路由函数并返回json对象。

list.route.js

const express = require('express');
const router = express.Router();

router.get('/', function(req, res) {
  var jsonobj = [ 
    {name:"john",gender:"male", score:345,},
    {name:"alice",gender:"female",score:678},
    {name:"paul",gender:"male",score:263},
    {name:"tia",gender:"female",score:620},
    {name:"michel",gender:"male",score:458},
    {name:"akbar",gender:"male",score:382},
    {name:"simon",gender:"male",score:193},
    {name:"albela",gender:"male",score:193}
  ]
    console.log('list route called')
    res.send(jsonobj) 
})
module.exports = router;

我尝试在 stackblitz.com 和 plunker 中创建项目,但无法针对某些设置相关问题复制问题。我观察到当我按下“t”、“j”、“u”等其他键时,它会起作用,但是当我按下“a”时,它不会显示“alice”和“albela”行。我必须继续输入,当输入 3 个字符时它会显示行。

控制台上也没有显示任何错误,所以我不知道。请看一下并建议我。

谢谢

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    我找到了解决方案here

    this.dataSource.filterPredicate 配置不正确,而且位置错误。我修改后的 listusers.component.ts 如下,

    listusers.component.ts

    import { Component, OnInit } from '@angular/core';
    import { ListService } from '../services/list.service';
    import { User } from '../model/user.model';
    import { MatTableDataSource } from '@angular/material';
    import { FormControl } from '@angular/forms';
    
    @Component({
      selector: 'listusers',
      templateUrl: './listusers.component.html',
      styleUrls: ['./listusers.component.css']
    })
    export class ListusersComponent implements OnInit {
      public users; 
      displayedColumns = [ 'position','name', 'gender', 'score'];
      dataSource: MatTableDataSource<User>;  
    
      constructor(private listsrv:ListService) { }
    
      ngOnInit() {      
        this.loaddata();
      }
    
      applyFilter(filterValue: string) {    
        this.dataSource.filter = filterValue.trim().toLowerCase();
      }
    
      loaddata(){
        console.log('in function loaddata') 
        this.listsrv.getList() 
          .subscribe(result => 
                      this.users = result, 
                      error => console.log('Error :',error), 
                      () => { console.log(this.users); 
                              this.dataSource = new MatTableDataSource(this.users);
                              //added below line
                              this.dataSource.filterPredicate = 
                                (data: User, filter: string) => data.name.indexOf(filter) != -1;
                    })
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-12
      • 2020-03-25
      • 2020-04-11
      • 2018-05-27
      • 1970-01-01
      • 1970-01-01
      • 2013-09-15
      相关资源
      最近更新 更多