角度2定制排序管道帮助我

时间:2017-11-18 14:48:27

标签: typescript ionic2 angular2-routing angular2-template angular2-directives

 *ngFor="let match of virtual | groupby : 'gameid'

ı有那样的代码。并且我有一个管道。 gameid就像23342341。

需要通过gameid对此数组进行asc排序。帮帮我们什么样的代码需要。

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

/**
 * Generated class for the GroupbyPipe pipe.
 *
 * See https://angular.io/api/core/Pipe for more info on Angular Pipes.
 */
@Pipe({
  name: 'groupby',
})
export class GroupbyPipe implements PipeTransform {
  /**
   * Takes a value and makes it lowercase.
   */
   transform(array: Array<string>, args: string): Array<string> {
        if (array !== undefined) {
            array.sort((a: any, b: any) => {
                if ( a[args] < b[args] ){
                    return -1;
                } else if ( a[args] > b[args] ) {
                    return 1;
                } else {
                    return 0;   
                }
            });
        }
        return array;
    }

}

和我的烟斗ts

ı在谷歌找到了代码,但它不起作用。任何人都会帮助我如何通过gameid(整数)对管道排序?

1 个答案:

答案 0 :(得分:0)

我添加了changeDetectorRef来检测本地更改。有时订阅内的数据更改不会反映出来。下面是我带有changeDetectorRef和slice的示例代码。使用两者并看到。 This is my working version here

import { Component, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
 term:string = "";
  topics = [
    {type:"NonFiction", name:"Titanic", num:2},
    {type:"Fiction", name:"Avatar", num:1},

    {type:"Tragedy", name:"MotherIndia",num:5},
  ];
  constructor(public ref : ChangeDetectorRef) { }

  ngOnInit() {
    this.addTopic();
  }

  addTopic(){
    setTimeout(()=>{
      console.log("triggered");
      this.topics.push({type:"share", name:"MotherIndia",num:3});
      this.topics=this.topics.slice();
      this.ref.detectChanges();
    },5000)
  }
}