代码之家  ›  专栏  ›  技术社区  ›  user944513

如何按角度排列姓氏列表?

  •  0
  • user944513  · 技术社区  · 8 年前

    我在Angular2中创建了一个项目列表。我想使用 custom fliter 或使用 pipe 。我们能用 lastname 我就这样试过了

    <ul *ngFor="let user of userList | lastname" class="userlist">
      <li>
        <span>{{user.name}}</span>
        <span>{{user.lastname}}</span>
        <span>{{user.age}}</span>
      </li>
    </ul>
    

    但它给了我错误的回复 请提出一种分类方法 https://stackblitz.com/edit/angular-fdxser?file=src%2Fapp%2Fapp.component.html

    3 回复  |  直到 8 年前
        1
  •  3
  •   Tobias Fuchs    8 年前

    以下是管道的外观(从链接)

    姓氏.pipe.ts:

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'lastname'
    })
    export class LastnamePipe implements PipeTransform {
    
      transform(values: any[]): any[] {
        return values.sort((a, b) => a.lastname.localeCompare(b.lastname));
      }
    }
    

    如果你想换一种方式 .reverse(); 返回语句或do b.lastname.localeCompare(a.lastname)

        2
  •  0
  •   Pradnya Sinalkar    8 年前

    在项目中添加以下排序管道。下面的管道是通用的,您可以将属性更改为sort以及ex。 皮特

    import {Pipe, PipeTransform} from '@angular/core';
    
    @Pipe({name: "sortBy"})
    export class SortPipe implements PipeTransform {
    
        transform(array: Array<any>, args: any): Array<any> {
            console.log("arra", array, '-- args:', args);
            if (array !== undefined) {
                let keys, order;
                if(typeof args == 'string'){ // use default sort criteria
                    keys = [args];
                    order = 1;
                }
    
                if(keys.length > 0){
                    array.sort((a: any, b: any) => {
                        if (a[keys[0]] < b[keys[0]]) {
                            return -1 * order;
                        } else if (a[keys[0]] > b[keys[0]]) {
                            return 1 * order;
                        } else {
                            return 0;
                        }
                    });
                }
            }
            return array;
        }
    }
    


    在pipemodule中声明s rot pipe如下: 管道模块

    import {NgModule} from '@angular/core';
    import {SortPipe} from './sort.pipe';
    
    @NgModule({
        imports: [],
        declarations: [SortPipe],
        exports: [SortPipe],
    })
    
    export class PipesModule {
        static forRoot() {
            return {
                ngModule: PipesModule,
                providers: [],
            };
        }
    }
    

    在app.module.ts.中注入pipemodule,html将是:

    <ul *ngFor="let user of userList | sortBy :'lastname'" class="userlist">
    
        3
  •  0
  •   Sourangshu Sengupta    8 年前

    您需要为此编写一个自定义管道。

    看看柯瑞肖的回答- angular-2-sort-and-filter

    推荐文章