how to use ngModel and ngIf for filtering data

6.3k Views Asked by At

I am new to ionic2 i need to filter the data based on what i enter , so i thought of using ngModel and ngIf. My JSON contains list of name and email and the code is below. Please tell me where I am going wrong, or if any other way please let me know.

In typescript I had initialized namefilter to particular name

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {Http , Headers} from '@angular/http';
import 'rxjs/add/operator/map'

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
})

export class HomePage {
  url:string;
  data:any[];
  namefilter:string='raj';

  constructor(public navCtrl: NavController , public http : Http) {
     this.getdata();
  }

  getdata() {
     this.url="http://example.com/json";
     this.http.get(this.url).map(res => res.json()).subscribe( res =>{
        console.log(res);
        this.data = res;
     }, err => {
        console.log(err);
     });
  }
}

This is the HTML:

<ion-list>
    <ion-item>
      <ion-label>Username</ion-label>
      <ion-input type="text" [(ngModel)] = 'namefilter' ></ion-input>
    </ion-item>
    <p> filtered by name : {{namefilter}} </p>
</ion-list>
  <div  *ngFor = ' let content of data ' >
    <ion-card  (click)="infoPage(content)" *ngIf="content.name === '{{namefilter}}' " >
      <h4>{{content.name}} : {{content.email}} </h4>
    </ion-card>
  </div>
2

There are 2 best solutions below

2
On BEST ANSWER

As @raj already commented, your *ngIf is wrong!

It should look like this:

<ion-card (click)="infoPage(content)" *ngIf="content.name === namefilter">

In *ngIf you have to use your variables without interpolation.

2
On

Just update your IF Condition. And I think there is no need to check type as well with value.

=== : will check value and type

== : will check only value

<ion-card  (click)="infoPage(content)" *ngIf="content.name == namefilter" >