Filtering items by value inside ngFor without writing Pipes

Dane picture Dane · Nov 21, 2017 · Viewed 14.4k times · Source

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 ?

Answer

Wedson Quintanilha da Silva picture Wedson Quintanilha da Silva · Apr 28, 2018

Use a filter function to filter the data:

filterFunction(your_collection): any[] {  
    return your_collection.filter(i => i.field.value === filterKey);
}

and in the template:

*ngFor="let value of filterFunction(datasource)"

Or use an existing component. See this thread:

::LINK EDITED::

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

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