首页 > 解决方案 > 模板与原始数组绑定时搜索功能而不改变原始数组?

问题描述

在我的模板中,我绑定了 this snapShotArray。变量正在通过snapShotArrayREST 端点调用填充数据。

<div class="col col-md-4 filter-by-cam">
      <input type="text" name="search" value="search" [(ngModel)]="search" #searchSnaps="ngModel"
        (keyup)="searchSnapshot(search)" />
        <button class="btn btn-primary" [disabled]="!search"
          (click)="searchSnapshot(searchSnaps.value)">Search
        </button>

    </div>

    <div *ngIf="!noData" class="game-board col-md-12">
        <div class="box camera-view-container col-md-3" *ngFor="let item of snapShotArray; let i = index; ">
          <img class="box-img camera-view" id="img{{i}}" src="{{item.image}}" crossOrigin="Anonymous">
          <div class="cam-feed">
            <span> {{item.name}}</span>
            <p>Last captured: {{item.lastCapturedDate}}</p>
          </div>
        </div>
      </div>

组件.ts:

public searchSnapshot(name: string) {
 let b = a.filter(item => item.name === name);
}

问题:

我想要的是搜索snapShotArray数组并返回一个与用户输入的文本匹配的特定对象。一旦用户清除文本框,用snapShotArray所有以前的对象或以前获取数据替换?

我知道这Filter不会改变原始数组。但是我现在卡住的地方是在将原始snapShotArray文件与模板绑定时过滤和替换原始文件。基本上是客户端的过滤功能。我如何实现这一目标?

标签: javascriptangulartypescriptfilterfind

解决方案


不要使用过滤器,在客户端使用管道。检查 https://angular.io/guide/pipes

<div *ngFor="let hero of (heroes | flyingHeroes)">
  {{hero.name}}
</div>

这是如何制作一个

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

import { Flyer } from './heroes';

@Pipe({ name: 'flyingHeroes' })
export class FlyingHeroesPipe implements PipeTransform {
  transform(allHeroes: Flyer[]) {
    return allHeroes.filter(hero => hero.canFly);
  }
}

对于您的具体情况:

<div class="box camera-view-container col-md-3" *ngFor="let item of (snapShotArray | searchFilter: searchValue); let i = index; ">

然后在您的组件中设置搜索值。您的过滤器应该非常简单,因为它只会返回过滤后的数组,而不会将其保存在任何地方。


推荐阅读