自定义管道对数组进行排序 [英] Custom pipe to sort array of array
本文介绍了自定义管道对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组,每个数组都有两个元素,即 arr [a [2]]
。索引0是名称,索引1是size。我希望管道根据大小(即索引1)对数组的数组进行排序。
I have a array of array having two elements each, i.e. arr[a[2]]
. Index 0 is name and index 1 is size . I want a pipe to sort the array of array according to size ie index 1 .
示例:
arr [ [ 'hello' , '1' ] , [ 'how' , '5' ] , [ 'you' , '12' ] , [ 'are' , '6' ] ]
管道的输出应为:
arr [ [ 'hello' , '1' ] , [ 'how' , '5' ] , [ 'are' , '6' ] , [ 'you' , '12' ] ]
HTML文件:
<p> {{items | custompipe }}</p>
推荐答案
使用管道进行排序不是一个好主意。在此处查看链接: https://angular.io/guide/pipes #appendix-no-filterpipe-or-orderbypipe
It's not a good idea to use a pipe for sorting. See the link here: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
相反,在组件中添加代码以执行排序。
Rather, add code in your component to perform your sort.
这里是一个例子。
import { Component, OnInit } from '@angular/core';
import { IProduct } from './product';
import { ProductService } from './product.service';
@Component({
templateUrl: './product-list.component.html'
})
export class ProductListComponent implements OnInit {
_listFilter: string;
get listFilter(): string {
return this._listFilter;
}
set listFilter(value: string) {
this._listFilter = value;
this.filteredProducts = this.listFilter ? this.performFilter(this.listFilter) : this.products;
}
filteredProducts: IProduct[];
products: IProduct[] = [];
constructor(private _productService: ProductService) {
}
performFilter(filterBy: string): IProduct[] {
filterBy = filterBy.toLocaleLowerCase();
return this.products.filter((product: IProduct) =>
product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);
}
ngOnInit(): void {
this._productService.getProducts()
.subscribe(products => {
this.products = products;
this.filteredProducts = this.products;
},
error => this.errorMessage = <any>error);
}
}
这篇关于自定义管道对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文