Dane
Dane

Reputation: 9552

Filtering items by value inside ngFor without writing Pipes

I have the following Component:

class MyComponent {
  public mode = 'v';
  readonly modes = ['v', 'a', 'd'];
  ....
}

Now I want to use an ngFor to display buttons for all modes in modes except the current mode stored in mode. I have the following code:

<button *ngFor="let othermode of modes">
  {{ othermode }}
</button>

I always want two buttons to be displayed, containing the remaining 2 modes. I tried this:

<button *ngFor="let othermode of modes.filter(elem => elem !== this.mode)">
  {{ othermode }}
</button>

but it isn't working. All questions I saw required to write a custom pipe for this feature, but isn't there any simple way to filter an array of strings, using just the values ?

Upvotes: 14

Views: 26084

Answers (3)

Use a filter function to filter the data:

filterFunction(allButtons): any[] {  
    return allButtons.filter(buttom => buttom !== this.mode);
}

and in the template:

<button *ngFor="let othermode of filterFunction(modes)">
  {{ othermode }}
</button>

To filter objects, I recommend using existing component. See this thread:

::LINK EDITED::

https://stackblitz.com/edit/angular-ivy-wngx-filter

https://stackblitz.com/edit/article-demo

Upvotes: 23

Vivek Doshi
Vivek Doshi

Reputation: 58573

You can use :

<ng-container *ngFor="let othermode of modes">
  <button *ngIf="othermode!=mode">
    {{ othermode }}
  </button>
</ng-container>

Upvotes: 16

Prithivi Raj
Prithivi Raj

Reputation: 2736

Use ng-template with ngIf, If you want to iterate the array with condition. Below is the sample code. you can find the working version here

<ng-template ngFor let-othermode [ngForOf]="modes">
<button *ngIf="othermode!=mode">
  {{ othermode }}
</button>
</ng-template>

Upvotes: 0

Related Questions