how to use ngModel and ngIf for filtering data

Issue

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>

Solution

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.

Answered By – slaesh

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.