javascript - 画廊搜索管道失败
问题描述
嗨,我已经完成了这个过滤器管道,我想从所有图像中查找我的图像名称和图像 ID,但它只是从第一张图像中查找名称和 ID。我的代码显然有任何问题。
This is my filter.pipe.ts class where I implement my search method
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(value: any, arg: any): any {
if (arg === '' || arg.length < 1) return value;
const resultPosts = [];
for (const imagen of value) {
if (imagen.name.toLowerCase().indexOf(arg.toLowerCase()) > -1) {
resultPosts.push(imagen);
}else if (imagen.imagenId.toLowerCase().indexOf(arg.toLowerCase()) > -1){
resultPosts.push(imagen);
};
return resultPosts;
}
}
}
My list.component.html where I have my input for searching:
<div class="row">
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text"name="filterImagen" placeholder="Search" [(ngModel)]="filterImagen">
<button class="btn btn-primary my-2 my-sm-0" type="submit">Search</button>
</form>
<div class="col-md-4" *ngFor="let imagen of imagenes | filter:filterImagen; index as i">
//when I look for the imagename or imageid, it just looks if my first image has the name I write on the searchbar
<div class="card mb-3 animated zoomIn">
<h3 class="card-header">{{imagen.name}}</h3>
<div class="card-body">
<h5 class="card-title"><b>ID: </b>{{imagen.imagenId}}</h5>
</div>
<div class="card-body text-center">
<img style="height: 200px; width: 100%; display: block;" src="{{imagen.imagenUrl}}" alt="Card image">
</div>
</div>
</div>
</div>
/* On my list.component.ts (here I just have a variable filter declared like: )*/
imagenes: Imagen[] = [];
filterImagen = ''; //just declared it here
//我已经在 app.module.ts 和我的类上导入了我的 FormsModule。
解决方案
你还记得在声明中添加管道吗?或者更好的是,从一个模块中导出它,然后将该模块导入到 app.module 中?
更新 - 我看到你的错误:) 你必须return resultPosts
离开 for 循环。
如果您有兴趣,为了清楚起见,我重构了管道:
import { Pipe, PipeTransform } from "@angular/core";
import { Imagen } from "./app.component";
@Pipe({
name: "filter"
})
export class FilterPipe implements PipeTransform {
transform(value: Imagen[], arg: any): any {
if (arg === "" || arg.length < 1) return value;
return value.filter(imagen => imagen.name.toLowerCase().indexOf(arg.toLowerCase()) > -1 ||
imagen.imagenId.toLowerCase().indexOf(arg.toLowerCase()) > -1
);
}
}
推荐阅读
- php - 登录时重定向路由 /login
- c - 如何使用递归打印此代码的结果?
- graphql - 当需要枚举(Apollo Server)时,如何将字符串传递给 GraphQL 查询?
- python - 使用python将多个txt文件合并到csv中
- python - 如何将数据透视表头添加到熊猫数据框中?
- python - 使用 Cython 将 np.ndarray 传递给 Fortran
- java - Payara 5,自定义 Restful json bean 属性
- sql-server - 从 SQL Server 中的 XML 列中提取值
- android-activity - 从一项活动转移到另一项活动
- flutter - 使用设置状态功能更新小部件