【问题标题】:Custom pipe to sort array of array自定义管道对数组进行排序
【发布时间】:2017-07-19 19:48:39
【问题描述】:

我有一个数组数组,每个数组有两个元素,即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>

【问题讨论】:

标签: angular angular2-pipe


【解决方案1】:

使用管道进行排序不是一个好主意。请参阅此处的链接: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);
    }
}

【讨论】:

  • 感谢您的回复,我喜欢您在复数视觉上的视频,它们对我的学习帮助很大。这个答案对我很有帮助,因为我一直在使用 OrderBySort 管道,即使我知道性能影响。很高兴看到一个更好的方法来做到这一点,我计划重构我的一些代码。谢谢!
  • 在此处查看 DeborahK 的评论,了解她在 stackoverflow.com/questions/46780843/…blogs.msmvps.com/deborahk/filtering-in-angular 上关于如何在不使用管道的情况下正确处理过滤的完整解决方案的链接。
猜你喜欢
  • 2019-05-26
  • 1970-01-01
  • 2022-07-11
  • 1970-01-01
  • 2018-05-12
  • 2014-04-19
  • 2012-06-24
相关资源
最近更新 更多