Home > OS >  Is it possible to show/hide item based on another item's value in a ngFor?
Is it possible to show/hide item based on another item's value in a ngFor?

Time:05-21

For example, I have a list like this:

items = [
  { key: "key0", value: "" },
  { key: "key1", value: "" },
  { key: "key2", value: "" },
  { key: "key3", value: "" },
  { key: "key4", value: "", dependency: "key2", dependency_value: "value2" },
  ...
]

The corresponding simple ngFor like this:

<tr *ngFor="item in items">
    <td>{{item.key}}: <input type="text" [(ngModel)]="item.value"></td>
</tr>

I want to show/hide "key4" (i.e., item[4]) depending on whether "key2" (i.e., items[2].value) equals "value2" dynamically based on user's input. Is it possible?

CodePudding user response:

You can do this.

<tr *ngFor="item in items; let i = index">
  <td *ngIf="
        i !== 4 ||
       (i === 4 && items[2].key === 'value2')
   ">
   {{item.key}}:
   <input type="text" [(ngModel)]="item.value">
  </td>
</tr>

OR

You can do this.

.ts file

filterData(items) {
  let newItems = [];
  let flag = false;
  for(let item in items){
     if(item.key == 'key2' && item.value == 'value2') {
        flag = true;
     }
     
     if(item.key != 'key4') {
        newItems.push(item);
     } else {
        if(!flag) newItems.push(item);
     }
  }
}

.html file

<tr *ngFor="item in newItems">
    <td>{{item.key}}: <input type="text" [(ngModel)]="item.value"></td>
</tr>

CodePudding user response:

(Edited) If I understood you correctly, this should work:

<tr *ngFor="item in items; let i = index">
   <td *ngIf=" i !== 4 ||  ( i === 4 && items[2].key === 'value2' )">
        {{item.key}}: <input type="text" [(ngModel)]="item.value">
   </td> 
</tr>

CodePudding user response:

It should works for your example:

<tr *ngFor="item in items; let i = index;">
   <ng-container *ngIf="i !== 4 || (i === 4 && items[2].value === item.dependency_value)">
      <td>
        {{item.key}}: <input type="text" [(ngModel)]="item.value">
      </td> 
   </ng-container>
</tr>
  • Related