javascript - 模板与原始数组绑定时搜索功能而不改变原始数组?
问题描述
在我的模板中,我绑定了 this snapShotArray
。变量正在通过snapShotArray
REST 端点调用填充数据。
<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
文件与模板绑定时过滤和替换原始文件。基本上是客户端的过滤功能。我如何实现这一目标?
解决方案
不要使用过滤器,在客户端使用管道。检查 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; ">
然后在您的组件中设置搜索值。您的过滤器应该非常简单,因为它只会返回过滤后的数组,而不会将其保存在任何地方。
推荐阅读
- android - 迁移 Room 2.1.0 -> 2.2.3(Android / Room / Java:预打包的数据库具有无效架构)
- django - Django 日志在文件大小达到 1050KB 后创建新的日志文件
- selenium - Selenium 块请求,页面加载前的脚本
- java - Jsoup 不会从网页中抓取整个 HTML
- physics - 当衍射光栅不垂直于光线时,衍射公式nλ=dsinθ如何变化?
- android - HttpUrlConnection.connect 失败
- memory - Keil 内存窗口
- javascript - 如何在环回操作挂钩中访问请求对象?
- c++ - GetOpt 在 Mac 上不起作用,没有显示任何参数
- sorting - 优化问题的适当数学模型:将堆叠的事物提升到同等水平