Search code examples
angulartypescriptfilterngfor

ngFor filter by text using trackby


I'm working on an angular 4 application and I have a big array of objects (like 200 rows) So I put a search input and the ngFor is related with a pipe that filters by name according to what you write in the input. Something like this

<input type="text" [(ngModel)]="searchtext" placeholder="Search">
<div *ngFor="let m of (devices | filterEquipments : searchtext)">{{ m.name }}</div>

The problem is when I start typing. Apparently filtering is very slow while rendering content in html. So, researching a solution, I could see that by using "trackBy" in the "ngFor" it is possible to optimize the result. The problem is that I don't know how to implement it correctly and if this can help me filter elements faster.

How can I implement a fast filter?


Solution

  • Maybe try to add some delay

    <input type="text" [value]="item.task_name"(keyup)="term$.next($event.target.value)">
    
    import ......
    
    import {Subject} from 'rxjs/Subject';
    import 'rxjs/add/operator/debounceTime';
    import 'rxjs/add/operator/distinctUntilChanged';
    import 'rxjs/add/operator/switchMap';
    

    @Component{( ... )} export class YourComponent {

      term$ = new Subject<string>();
    
      constructor() {
       this.term$
         .debounceTime(1000)
         .distinctUntilChanged()
         .switchMap(term => /*do something*/);
      }
    }