簡體   English   中英

從Angular數組中搜索過濾器

[英]Search filter from array on Angular

我有一個存儲汽車列表的應用程序。我想將Search屬性添加到我的項目中。我決定在我的searchBox中使用pipe和ngModel來實現這一點。在管道上,我有const obj變量,它可以根據需要從組件根據ngModel過濾數組。但是angular給出了錯誤,並說ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined: [object Object],[object Object],[object Object]'. Current value: 'undefined: '. ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined: [object Object],[object Object],[object Object]'. Current value: 'undefined: '. 我猜它最初是不確定的,這就是為什么它發生的原因。但是我添加了if塊來檢查是否未定義,而不是得到這個錯誤。這是我下面的組件和管道

汽車清單Component.html

  <form class="example" style="margin:auto;max-width:200px">
    <input [(ngModel)]="nameBrand" type="text" placeholder="Search.." name="search2">
  </form>
  <div class="row">
    <div class="col-xs-12">
      <app-car-item
        *ngFor="let carEl of cars | orderName:nameBrand ;let i = index"
        [car]="carEl"
        [index]="i"
        >
      </app-car-item>
    </div>
  </div>

OrderPipe.ts

@Pipe({
  name: 'orderName',
})
export class OrderNamePipe implements PipeTransform{
  constructor(private carService:CarService)
  {

  }
  transform(value: any, arg1: any) 
   {       
      const obj = this.carService.getCars().filter(s => s.brand.includes(arg1));      
      if(obj)
      {
           this.carService.setCars(obj);
     }
    }
  }

汽車list.component.ts

  ngOnInit() {
    this.subscription=this.carService.carsChanged
    .subscribe(
     (cars:Car[])=>
     {
       this.cars=cars;
     }
    );
    this.cars = this.carService.getCars();
    }

Car.Service.ts

        export class CarService
    {
       carsChanged=new Subject<Car[]>();
       private cars: Car[]=[
            new Car(
               'Dodge Viper SRT10',
               'Coupe',
               2017,
               645,
               600,
               'Gasoline',
               'Used',
               'http://cdn-ds.com/stock/2010-Dodge-Viper-SRT10-ACR-Ltd-Avail-Akron-OH/seo/ECL2585-1B3AZ6JZ6AV100278/sz_88264/b22eddbbf045c389bd39e4ede1328f13.jpg',
               970000
           ),
           new Car(
            'Chevrolet Camaro',
            'Coupe',
            2012,
            432,
            600,
            'Gasoline',
            'Used',
            'https://carimages.com.au/MdzpzcZ7iNNuMu7RlH3Eg5t30CM=/fit-in/800x540/filters:stretch(FFFFFF)/vehicles/used/2018/CHEVROLET/CAMARO/2018-CHEVROLET-CAMARO-used-78-JWF447-1.jpg',
            274000
        ),
        new Car(
            'Bentley Continental-GT',
            'Coupe',
            2018,
            601,
            489,
            'Gasoline',
            'New',
            'https://cdn1.autoexpress.co.uk/sites/autoexpressuk/files/2017/11/4bentleycontinentalgt.jpg',
            4150000
        ) 
       ]
       constructor()
       {}
       setCars(cars: Car[]) {
        this.cars = cars;
        this.carsChanged.next(this.cars.slice());
 getCars()
   {
    return this.cars;
   }
      }

汽車Model.ts

export class Car{
    public brand:string;
    public type:string;
    public year:number;
    public bhp:number;
    public torque:number;
    public fuel:string;
    public condition:string;
    public imageUrl:string;
    public price:number;

    constructor(brand:string,type:string,year:number,bhp:number,torque:number,fuel:string,condition:string,imageUrl:string,price:number)
    {
        this.brand=brand;
        this.type=type;
        this.year=year;
        this.bhp=bhp;
        this.torque=torque;
        this.fuel=fuel;
        this.condition=condition;
        this.imageUrl=imageUrl;
        this.price=price;
    }
}

我認為使用管道內部服務中的數據並不是一種好方法。 試試這個管道,

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

@Pipe({
    name: 'orderName'
})

@Injectable()
export class OrderNamePipe implements PipeTransform {
    transform(items: any[], field: string, value: string): any[] {
        if (!items) {
            return [];
        }
        if (!field || !value) {
            return items;
        }
        return items.filter(singleItem => singleItem[field].toLowerCase().includes(value.toLowerCase()));
    }
}

這樣,您的管道可以重復使用。 將模板更改為

<app-car-item
    *ngFor="let carEl of cars | orderName : 'brand' : nameBrand ;let i = index"
    [car]="carEl"
    [index]="i"
    >
</app-car-item>

指定“品牌”是因為您需要根據該字段進行過濾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM