我有一个数组,每个数组有两个元素,即arr[a[2]]
。索引0是名称,索引1是大小。我想要一个管道根据大小即索引1对数组数组进行排序。
示例:
arr [ [ 'hello' , '1' ] , [ 'how' , '5' ] , [ 'you' , '12' ] , [ 'are' , '6' ] ]
管道输出应为:
arr [ [ 'hello' , '1' ] , [ 'how' , '5' ] , [ 'are' , '6' ] , [ 'you' , '12' ] ]
HTML文件:
<p> {{items | custompipe }}</p>
答案 0 :(得分:3)
使用烟斗进行分拣不是一个好主意。请参阅此处的链接:https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
而是在组件中添加代码以执行排序。
这是一个例子。这个过滤器,但您可以将其更改为排序。
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);
}
}