如何在 ngFor 结果中搜索?

How to search in ngFor results?

我有一个 JSON 对象,我需要迭代它并包含一个搜索功能,该功能显示键和在该键中搜索的值。

我使用管道并通过遍历键及其值实现了这一点。

COMPONENT.HTML:

<input type="text" class="form-control" placeholder = "Search"[(ngModel)] = "query" id = "listSearch"  #search >

      <ul>
      <li * ngFor="let key of objectKey()" >
        <span>{{ key }}</span>
          < table >
          <tr * ngFor="let item of (testData[key] | LockFilter:'appName': search.value) as result" >
            <td>{{ item.appName }}</td>
              < /tr>
              < /table>
              < /li>
              < /ul>  

COMPONENT.TS:

testData = {
  "MyCat1": [
    {
      "appName": "Myapp1",
      "appCatName": "MyCat1"
    },
    {
      "appName": "Myapp2",
      "appCatName": "MyCat1"
    }
  ],
  "MyCat2": [
    {
      "appName": "Myapp3",
      "appCatName": "MyCat2"
    },
    {
      "appName": "Myapp4",
      "appCatName": "MyCat2"
    }
  ]
}
objectKey() {
  return Object.keys(this.testData);
}

PIPE.TS:

transform(items: any[], field: string, value: string): any[] {

  if (!items) return [];
  if (!value) return items;

  return items.filter(str => {
    return str[field].toLowerCase().includes(value.toLowerCase());
  });

}

Expected Results BEFORE SEARCH: MyCat1: Myapp1 Myapp2

MyCat2: Myapp3 Myapp4

AFTER SEARCH: (search string '1') MyCat1: Myapp1

Current Output Image

试试这个:

<input [(ngModel)]="search" />
<ul>
    <li *ngFor="let key of objectKey()" [hidden]="!(testData[key] | LockFilter:'appName': search).length">
        <span>{{ key }}</span>
        <table>
            <tr *ngFor="let  item of (testData[key] | LockFilter:'appName': search) as result">
                <td> {{ item.appName }}</td>
            </tr>
        </table>
    </li>
</ul>

Working Demo

试试这个

  // check if exists and will return the keys
  objectKey(value) {
    return Object.entries(this.testData)
      .filter(data=> (data[1].filter(item=> item[value].includes(this.search)).length))
      .map([KEY, VAL] => KEY)
  }

在HTML(相同代码)

  <ul>
    <li *ngFor="let key of objectKey('appName')"  >
      <span   >{{ key }}</span>
        <table>
          <tr *ngFor="let  item of (testData[key] | LockFilter:'appName': search) as result" >
              <td >   {{ item.appName }}</td>
          </tr>
        </table>
    </li>
  </ul>  

Working Demo