0

I am looking for a simple way to filter the *ngFor results from a search box input. The same way as in AngularJS this would work: ng-model="searchBox" / ng-repeat="x in y | filter:searchBox"...

My code is:

<input type="text">
<article *ngFor="let x of y | async | reverse">
    <p>Name: {{x.firstName}} {{x.secondName}}, City: {{x.city}}, Phone: {{x.phone}}</p>
</article>
Alex
  • 1
  • You mean like a custom filter? if so, maybe this will help https://stackoverflow.com/questions/34164413/how-to-apply-filters-to-ngfor – amnah Aug 11 '21 at 15:26
  • My goal is a little bit different - when you write "a" in the input every object that contains "a" in its values should be shown. – Alex Aug 11 '21 at 15:34

3 Answers3

0

The easiest way is using *ngIf to filter your result without having to make a custome pipe, here's how your code would look like

<input type="text">
<article *ngFor="let x of y | async | reverse">
  <p *ngIf="x.param == yourFilteredValue">Name: {{x.firstName}} {{x.secondName}}, City: {{x.city}}, Phone: {{x.phone}}</p>
</article>

Or you could wrap your entire article body with a div having an *ngIf expression.

Mohamed Karkotly
  • 1,364
  • 3
  • 13
  • 26
  • This solution kind of works but the idea is if there is a value "London" in the object and you write "Lon" to have it shown. With "==" it will be shown only if you write the full "London" in the input... – Alex Aug 11 '21 at 16:04
  • @Alex - Try the `.startsWith(yourFilteredValue)` on your param. It should go something like this: `*ngIf="x.param.startsWith(yourValue)"` – Mohamed Karkotly Aug 11 '21 at 16:12
  • Thanks I used your example with includes() and it did the job! Unfortunately I can not cast a vote because of my reputation. :) – Alex Aug 14 '21 at 09:17
  • @Alex - That's awesome! Glad to know that helped somehow. – Mohamed Karkotly Aug 14 '21 at 14:12
0

You can also try keeping the filter logic inside ts file and then return an array which contains the required items. Then you could loop them and display as needed.

vsnikhilvs
  • 456
  • 1
  • 3
  • 10
0

In template

  <input type="text" [(ngModel)]="searchItem">
  <div *ngIf="(data$| async)?.length;" >
    <article *ngFor="let x of y | async | myFilter: searchItem">
     <p>Name: {{x.firstName}} {{x.secondName}}, City: {{x.city}}, Phone 
      {{x.phone}}</p>
    </article>
 ​</div>

The custom pipe

 transform(value: any[], ...args: any): any {
    let searchItem = ''
    if(args.length)  searchItem = args[0].toLowerCase()
    return value.filter((data:any)=> data.firstName.toLowerCase().includes(searchItem));
  }

you can change the key (data.firstName) to match whatever you would like to filter with.

amnah
  • 444
  • 2
  • 6