gpt4 book ai didi

Angular 4 FilterBy 管道

转载 作者:搜寻专家 更新时间:2023-10-30 22:03:41 31 4
gpt4 key购买 nike

我正在尝试模拟 AngularJS 中的 OrderBy。

给定这种数组。我需要按 car_category 过滤汽车。

[
{
"car_category": 3,
"name": "Fusion",
"year": "2010"
},
{
"car_category": 2,
"name": "Mustang",
"year": "2010"
},
{
"car_category": 3,
"name": "Fiesta",
"year": "2010"
},
]

这是我的代码到目前为止的样子

car.component.html

<div *ngIf="products">
<ul *ngFor="let product of products | filterBy: car_category">
<li>{{car.name}}</li>
</ul>
</div>

car.component.ts

import { Component, OnInit } from '@angular/core';
import { CarService } from '../car.service';
import { ICars } from '../ICars';
import { FilterByPipe } from '../filter-by.pipe';

@Component({
selector: 'app-home-page',
templateUrl: './car.component.html',
styleUrls: ['./car.component.css']
})
export class CarComponent implements OnInit {
cars: Array<ICars>;
errorMessage: string;
filteredCars: any;
car_category= 3;

constructor(private _carService: CarService) { }
ngOnInit() {
this._carService.getCars()
.subscribe(
cars => this.cars = cars,
error => this.errorMessage = error
);
}

}

filet-by.pipe.ts

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

@Pipe({
name: 'filterBy'
})
export class FilterByPipe implements PipeTransform {

transform(value, args) {
if (!args[0]) {
return value;
} else if (value) {
return value.filter(item => {
// tslint:disable-next-line:prefer-const
for (let key in item) {
if ((typeof item[key] === 'string' || item[key] instanceof String) &&
(item[key].indexOf(args[0]) !== -1)) {
return true;
}
}
});
}
}

}

我的管道需要如何重构?

更新这就是我的 pipe 现在的样子。注意汽车是数字,年份显示为字符串

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

@Pipe({
name: 'filterBy'
})
export class FilterByPipe implements PipeTransform {

transform(value, args) {
if (!args[0]) {
return value;
} else if (value) {
return value.filter(item => {
// tslint:disable-next-line:prefer-const
for (let key in item) {
if ((typeof item[key] === 'number' || item[key] instanceof Number) &&
(item[key].indexOf(args[0]) !== -1)) {
return true;
}
}
});
}
}

}

最佳答案

编写自定义通用管道可能很棘手。如果您查看 Angular 1 source code ,你会明白我的意思。

因此我建议使用库,例如​​ ng-pipes .老实说,我还没有测试过 Angular 2 版本,但它对于 Angular 1 来说非常方便。

关于Angular 4 FilterBy 管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43633367/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com