首页 > 解决方案 > 画廊搜索管道失败

问题描述

嗨,我已经完成了这个过滤器管道,我想从所有图像中查找我的图像名称和图像 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。

标签: javascriptangulartypescriptpipe

解决方案


你还记得在声明中添加管道吗?或者更好的是,从一个模块中导出它,然后将该模块导入到 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
    );
  }
}

推荐阅读