在一系列嵌套对象的情况下,如何在角组件中使用数据过滤



我想根据我的项目的YouTube教程视频创建一个即时搜索功能。您可以在这里找到书面版本。

与以下JSON结构(同一教程系列使用(的一切正常:

[
 0: {
  id: 123,
  firstName: "Jon",
  lastName: "Doe",
  ...
 },
 1: {
  id: 321,
  firstName: "Tom",
  lastName: "Someone",
  ...
 }
]

但是,我需要在项目中使用以下JSON结构,并且无法对其进行修改(通过REST API获取(:

[
 0: {
  employee: {
    id: 123,
    firstName: "Jon",
    lastName: "Doe",
    ...
  },
  someOtherObject: {
    key1: value1,
    key2: value2,
    ...
  },
  anotherObject: {
    ...
  }  
 },
 1: {
   employee: {
    id: 321,
    firstName: "Tom",
    lastName: "Someone",
    ...
  },
  someOtherObject: {
    key1: value1,
    key2: value2
  },
  anotherObject: {
    ...
  }  
 },
]

搜索功能与上述JSON结构不起作用。

我想在具有相同即时搜索体验的大多数嵌套对象中进行搜索。

更新:

employee.component.ts看起来与链接指南相同。

员工看起来像这样:

export class Document {
    _id: string;
    _rev: string;
    employee: any[];
    otherArray: any[];
    anotherArray: any[];
}

HTML看起来像这样:

<div *ngFor="let employee of filteredEmployees">
    {{ employee.firstName + ' ' + employee.lastName }}
</div>

使用管道

结合文本输入,一些模型绑定和管道,您应该能够实现我所追求的目标。

在HTML

<input id="filter_input" type="text" [value]="filterBy" placeholder="Filter by {{filterOnText}}" (input)="filterBy = $event.target.value">
<div *ngFor="let employee of filteredEmployees | filter:filterOnKey:filterBy ">
    {{ employee.firstName + ' ' + employee.lastName }}
</div>

然后在组件中

filterOnText: string;
filterOnKey: string;
filterBy = '';

然后管道

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'filter',
    pure: false
})
export class FilterPipe implements PipeTransform {
/*____________________________________________________________
* usage: *ngFor="let license of licenses  | filter:'Name':filterBy;
* 'Name' is the name of the column in list.
* filterBy obtained from input box
*_____________________________________________________________
*/
transform(items: any, property: any, term: any): any {
    if (!term) {
        return items;
    }
    const result = items.filter(function (item) {           
            if (item[property] === null) {
                return items;
            }
            if (item[property].toString().toLowerCase().includes(term.toLowerCase())) {
                return true;
            }
            return false;
        });
        if (result.length === 0) {
            return [-1];
        }
        return result;
    }
}

最新更新