【问题标题】:How to filter values in objects of array in angular如何以角度过滤数组对象中的值
【发布时间】:2019-07-22 21:28:34
【问题描述】:

如何以角度过滤数组对象中的值。 (例如:我需要过滤staffAttendanceList的staff对象中的值,我不知道如何传递正确的参数来过滤staff值。)

打字稿

1)在.ts中:

   attendanceStatus:any;
   staffAttendanceList: StaffAttendance[] = [
      status:false,
      staff:{
       staffId:"ERP1001",
       firstName:'Rahul',
       lastName:'Sharma'
       }
     ];

HTML:我使用了带参数('staff')的过滤管道,但它不起作用。

2) 在 HTML 中:

    <table>
      <tbody>
        <tr*ngFor="let staffAttendance of staffAttendanceList|filter:searchStaffAttendance:'staff.staffId';
        index as i">
          <td>{{i+1}}</td>
          <td>{{staffAttendance.staff.staffId}} 
          </td>
          <td>{{staffAttendance.staff.firstName}} 
           {{staffAttendance.staff.lastName}}</td>
        </tr>
      </tbody>
    </table>

过滤器管道:我创建了一个自定义过滤器管道来搜索人员值。

3)在过滤管中:

import { PipeTransform, Pipe } from "@angular/core";

@Pipe({
    name:'filter'
})
export class FilterPipe implements PipeTransform {
    transform = (value:[],filterString:any,propName:any):any => { 
        let inputValue = [];
        if(filterString === undefined || filterString === '' || 
           value.length == 0){
            return value;
        }
        for(const item of value){
            if(item[propName] === filterString){
                inputValue.push(item);
            }          
        }
        return inputValue;
    }      
}

【问题讨论】:

标签: angular filter pipe


【解决方案1】:

你应该使用过滤器而不是 for。如果您一直希望按 Id 进行过滤,请不要将其作为参数传递,但如果可以更改,请添加其他参数。假设propName 是staff,staffId 是propNameId 的新参数

用这个替换你的管道,不要忘记在 html 中为 Id 添加一个参数:

export class FilterPipe implements PipeTransform {
    transform = (value:[],filterString:any,propName:any, propNameId):any => { 
        let inputValue = [];
        if(filterString === undefined || filterString === '' || 
           value.length == 0){
            return value;
        }
        inputValue = value.filter(item => {
            item[propName][propNameId] === filterString;
        })
        return inputValue;
    }      
}

过滤器将返回 item.staff.staffId 等于任何 filterString 的每个项目。

【讨论】:

    猜你喜欢
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多