Search code examples
typescriptionic2angular2-routingangular2-templateangular2-directives

angular 2 custom sort pipe help me plase


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

ı have like that code. and ı have a pipe . gameid is like 23342341 .

ı need to asc sorting this array by gameid. help me guys . what kind a code ı need.

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;
    }

}

and its my pipe ts

ı found the code in google but its not work. any one will be help me how can ı sort my array on pipe by gameid (integer) ?


Solution

  • I have added changeDetectorRef to detect changes in local. sometimes data changes inside subscribe will not reflect. Below is my sample code with changeDetectorRef and slice. use both and see. 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)
      }
    }