Search code examples
angularangular6angular-pipe

To display json data in alphabetical order


This is my(customer.component.html)file

<input type="text" [(ngModel)]="name" (ngModelChange)="onNameChange()">

<div *ngFor="let s of filteredScreenshots">
  {{s | json}}
</div>

<mat-card class="example-card" *ngFor="let filteredScreen of 
 filteredScreens | filter : filteredScreen;"  let i = index>

  <mat-card-header>
    <div mat-card-avatar class="example-header-image" >
       <img mat-card-image class="list-img" src=" 
          {{filteredScreen?.img}}">
    </div>
    <mat-card-content class="names">
      {{ filteredScreen?.name }} 
    </mat-card-content>
  </mat-card-header>
</mat-card>

This (customer.component.ts)file

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http'; 
import { map } from 'rxjs/operators'
import * as _ from 'lodash';


@Component({
  selector: 'ylb-customer',
  templateUrl: './customer.component.html',
  styleUrls: ['./customer.component.css']
})

export class CustomerComponent  {

  spaceScreens: Array<any>;
  filteredScreens = [];
  name: string;


  constructor(private http:Http){
    this.http.get('assets/app.json').pipe(
            map(response => response.json().screenshots)
        )
        .subscribe(res => {
            this.spaceScreens = res; 
            this.filteredScreens = res;
    });
  }

  onNameChange() {
    this.filteredScreens = _.filter(this.spaceScreens, (screenshot) => {
    const name = screenshot['name'];
    const filteredName = this.name.toUpperCase();
    return name === undefined ? false : name.toUpperCase().startsWith(filteredName);
    });
  }


}

I have created json file called app.json inside(assets)folder,The app.json file code as follows

{   
  "screenshots":[ 

    {
        "img":"assets/img/json_2.jpg",
        "name":"Virat Kohli"
    },

    {
        "img":"assets/img/json_2.jpg",
        "name":"Joe Root"
    },

    {
        "img":"assets/img/json_2.jpg",
        "name":"Adam Gilchrist"
    },
    {
        "img":"assets/img/json_2.jpg",
        "name":"Kevin Peterson"
    },

    {
        "img":"assets/img/json_2.jpg",
        "name":"Misbhah-Ul-Hak"
    },

    {
        "img":"assets/img/json_2.jpg",
        "name":"ABD Develliers"
    },
    {
        "img":"assets/img/json_2.jpg",
        "name":"Ben stokes"
    },

    {
        "img":"assets/img/json_2.jpg",
        "name":"Chris Gayle"
    }

  ]        
}

Created 2 pipe file(sort.pipe.ts and filter.pipe.ts)inside folder called shared

(sort.pipe.ts)is as follows

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
  name: "sort"
})
export class ArraySortPipe  implements PipeTransform {
  transform(array: any[], field: string): any[] {
    array.sort((a: any, b: any) => {
    if (a[field] < b[field]) {
        return -1;
    } else if (a[field] > b[field]) {
        return 1;
    } else {
        return 0;
    }
    });
    return array;
  }
}

(filter.pipe.ts)is as follows

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string): any[] {
    if(!items) return [];
    if(!searchText) return items;
    searchText = searchText.toLowerCase();
    return items.filter( it => {
      return it.toLowerCase().includes(searchText);
    });
  }
}

and imported these pipe files in(app.modules.ts) like this

import { FilterPipe} from './shared/filter.pipe';
import { ArraySortPipe} from './shared/sort.pipe';

@NgModule({
  declarations: [
  FilterPipe,
  ArraySortPipe
],  

I have to achieve this following 2 conditions 1)I want to display the data present in app.json file in alphabetical order 2)How can i apply search for last name of the name string,i mean suppose i want to search virat kohli,how can i search it by typing only kohli

I tried the above code for this 2 condition but nothing goes right,Please figure out is any mistake in this code.But searching is happening is fine.


Solution

  • Do the below changes and you will get the output.

    You can simply sort your http response in alphabetical order.

    constructor(private http:Http){
        this.http.get('assets/app.json').pipe(
                map(response => response.json().screenshots)
            )
            .subscribe(res => {
                this.spaceScreens = this.sortByName(res); 
                this.filteredScreens = this.sortByName(res);
        });
      }
    
      onNameChange() {
        this.filteredScreens=_.filter(this.spaceScreens,(item)=>{
          console.log(this.name)
    

    return item.name.toLowerCase().indexOf(this.name.toLowerCase())>-1; });

      }
      sortByName = function(users) {
        const byName = function(user1,user2) {
          return user1.name.localeCompare(user2.name);
        };
        return users.slice().sort(byName);
      };
    

    And html is

    <div class="example-card" *ngFor="let filteredScreen of 
     filteredScreens "  let i = index>
    
    
        <div mat-card-avatar class="example-header-image" >
           <img mat-card-image class="list-img" src=" 
              {{filteredScreen?.img}}">
        </div>
          {{ filteredScreen?.name }} 
    
    </div>