在我的模板中,我绑定了这个snapShotArray
。 REST端点调用正在用数据填充snapShotArray
变量。
<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>
Component.ts:
public searchSnapshot(name: string) {
let b = a.filter(item => item.name === name);
}
问题:
我想要的是搜索snapShotArray
数组并返回一个与用户输入的文本匹配的特定对象。用户清除文本框后,将snapShotArray
替换为所有先前的对象还是获取数据?
我知道Filter
不会使原始数组变异。但是,我现在遇到的问题是将原始snapShotArray
与模板绑定时进行过滤和替换。基本上是客户端的过滤器功能。我该如何实现?
答案 0 :(得分:2)
不要使用过滤器,请在客户端使用管道。校验 https://angular.io/guide/pipes
\b\w+\((.*?)\)
下面是制作方法
<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);
}
}
然后在组件中设置搜索值。您的过滤器应该非常简单,因为它只会返回过滤后的数组,而不会将其保存在任何地方。
答案 1 :(得分:1)
始终使用管道进行过滤
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'snapshotFilter' })
export class SnapshotFilterPipe implements PipeTransform {
transform(snapshotArr: [] , searchValue : string) {
return snapshotArr.filter(snapshot=> {
snapshot.name === searchValue
});
}
}
此处是HTML
<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 | snapshotFilter : searchValue ; 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>
以及您的组件
public searchSnapshot(search: string) {
this.searchValue = search;
}
不要忘记在应用模块中包含管道