如何以角度过滤表格数据

时间:2019-12-13 06:36:11

标签: javascript angular

export class EmployeeDetailsComponent implements OnInit {
  employees: any = [];
  public errorMsg;
  // you can define also below
  // errorMsg:any = [];
  constructor(private _employeeService: EmployeeService) {}

  ngOnInit() {
    this._employeeService.getEpmloyees().subscribe(
      data => (this.employees = data),
      error => (this.errorMsg = error)
    );
  }

  applyFilter(filterValue: string) {
    this.employees.filter = filterValue.trim().toLocaleLowerCase();
  }
}
<body>
  <p><input type="text" (keyup)="applyFilter($event.value)"></p>
  <table border="1">
    <tr>
      <th>ID</th>
      <th>NAME</th>
      <th>AGE</th>
      <th>Mobile</th>
    </tr>

    <tbody *ngFor="let employee of employees; i as index">
      <tr>
        <td>{{employee.id}}</td>
        <td>{{employee.name}}</td>
        <td>{{employee.age}}</td>
        <td>{{employee.mob}}</td>
      </tr>
    </tbody>
  </table>
</body>

上面是我的代码,我只是想知道出什么问题了 在过滤器方法中,我需要真正进行更改才能使其工作。 以及如何获取经过适当过滤的数据?

4 个答案:

答案 0 :(得分:2)

尝试一下

export class EmployeeDetailsComponent implements OnInit {
      employees: any = [];
      allEmployees:any=[];
      public errorMsg;
      constructor(private _employeeService: EmployeeService) {}

      ngOnInit() {
        this._employeeService.getEpmloyees().subscribe(
          data => (
              this.employees = data,
              this.allEmployees=data;//You don't want to override you search data with all employee list
          ),
          error => (this.errorMsg = error)
        );
      }

      applyFilter(filterValue: string) {
         let filterValueLower = filterValue.toLowerCase();
         if(filterValue === '' ) {
             this.employees=this.allEmployees;
         } 
         else {
           this.employees = this.allEmployees.filter((employee) => employee.name.includes(filterValueLower)
         }
      }
    }

答案 1 :(得分:1)

我猜想过滤字符串应该应用于数组中的某个字段以过滤数据,例如名称:

applyFilter(filterValue: string) {
    this.employees.filter(i => i.name.toLowerCase().includes(filterValue.toLowerCase());
  }

您也不想在每个按键上都应用过滤器,直到您想使用反跳。

答案 2 :(得分:1)

根据需要,需要在filter()数组上使用this.employees函数,并根据需要过滤{{1}的全部或特定属性)的属性}对象,您可以设置过滤条件。然后您的代码将如下所示:

employee

答案 3 :(得分:0)

尝试这样

template.html

<input type="text" (keyup)="applyFilter($event.target.value)"></p>

component.ts

applyFilter(filterValue: string) {
    let filterValueLower = filterValue.toLowerCase();
    if(filterValue === '' ) {
        this.employees
    } else {
       this.employees = this.employees.filter((employee) => 
                        employee.id.includes(filterValueLower) || 
                        employee.name.toLowerCase().includes(filterValueLower) || 
                        employee.age.toLowerCase().includes(filterValueLower) || 
                        employee.mob.toLowerCase().includes(filterValueLower));
  }
 }