'Angular show hide with combine condition

I have an array of object need to show hide based on filter like below:

HTML CODE:
    Filter:
        <div (click)="filter(1)"> F1 </div> 
        <div (click)="filter(2)"> F2 </div> 
        <div (click)="filter(3)"> F3 </div> 
        <div (click)="filter(4)"> F4 </div> 
    
      <div *ngFor="let data of datas">
            <span *ngIf="data.show">
            {{data.name}}
            </span>
        </div>

ts Code:
 this.datas = `[{'name':'product one','filter':'1'},{'name':'product two','filter':'2'},{'name':'product three','filter':'3'},{'name':'product three','filter':'3'},{'name':'product','filter':''},{'name':'product','filter':''},{'name':'product one','filter':'1'},{'name':'product'}]`

filter(query){
    this.datas.forEach(function (element, index) {
        if (element.filter == query ) {
            element.show = true;
        } else {
            element.show = false;
    }

I have tried the above approach it's not working . Expected like:

  1. By default display all product.
  2. Filter is toggle(on/off)
  3. Need to filter like (F1 & F2 & F3) at the same time like combination


Solution 1:[1]

The array objects do not have the show property that you test in the *ngIf directive

Solution 2:[2]

Rather simple, really.

I made you a small stackblitz app. But you also really, really need to work on your code. Even as a description for your help, this is just pretty messy.

I didn't code your "Multiple Selections" for you.

https://stackblitz.com/edit/angular-ivy-fbpgdv?file=src/app/app.component.ts

Solution 3:[3]

Observation/Suggestions :

  • Instead of adding a new property show. You can easily achieve that by filtering out the datas array based on the value passed in the filter() method.
  • Instead of modifying the original array, you can make a deep copy and do the operation on click on filter().

Working Demo : https://jsfiddle.net/srvpw2bo/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matheus Alencar
Solution 2
Solution 3 Rohìt Jíndal