Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 filter ngFor elements according to life user input?

Tags:

angular

is theire a plugin to filter elements rendred using *ngFor according to live user input after each keyup event ?

like image 836
user2080105 Avatar asked Feb 22 '17 16:02

user2080105


1 Answers

There is no plugin needed!

Two possible ways:

  • use a filter function and have a filtered array of your data (better performance!)
@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <input (keyup)="search($event.target.value)" />
      <div *ngFor="let d of filteredData">
        {{ d }}
      </div>
    </div>
  `,
})
export class App {
  name:string;
  data = [
    "val1",
    "val2",
    "val3",
    "val4",
    "val5",
    "val6",
    "test",
    "huhu"
  ];
  filteredData = this.data;

  constructor() {
    this.name = 'Angular2'
  }

  search(val: any) {
    if (!val) this.filteredData = this.data;

    this.filteredData = this.data.filter(d => d.indexOf(val) >= 0);
  }
}

live demo: https://plnkr.co/edit/9NtT6Z4RIg4BR1BVfh7r?p=preview

  • or using a Pipe
@Pipe({ name: 'filter' })
export class FilterPipe implements PipeTransform {
  public transform(values: any[], filter: string): any[] {
    if (!values || !values.length) return [];
    if (!filter) return values;

    return values.filter(v => v.indexOf(filter) >= 0);
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <input [(ngModel)]="filterString" />
      <div *ngFor="let d of (data | filter: filterString)">
        {{ d }}
      </div>
    </div>
  `,
})
export class App {
  name:string;
  data = [
    "val1",
    "val2",
    "val3",
    "val4",
    "val5",
    "val6",
    "test",
    "huhu"
  ];

  filterString = '';

  constructor() {
    this.name = 'Angular2'
  }
}

live demo: https://plnkr.co/edit/usgvA1hpqQ06zJxMrx4f?p=preview

like image 157
slaesh Avatar answered Nov 16 '22 12:11

slaesh