Search code examples
angulartypescriptangular-ng-if

Angular - How to hide and show content with a boolean for 'this' item in a ngFor loop


I have an ngFor loop displaying several list items. Each list item contains a title. It also contains an input with the title inside it which I want hidden. When I hit an edit button, I want the input for that selected item to show, none of the others. What's the best way to approach this?

Below is what I have so far. However, when initiating 'editItem' and setting 'editable' to true, the input box for all items appears, not just the one I clicked on.

editable = false;

editItem(){
  this.editable = true;
}
<ul>
  <li *ngFor="let item of items | async">
    <div class="item">
      <div class="title"> {{ item.item_title }}</div>
      <input #newItemName type="text" [(ngModel)]="this.item.item_title" *ngIf="editable"/>
      <i aria-hidden="true" (click)="editItem()"></i>
     </div>
  </li>
</ul>

Any assistance would be greatly appreciated :)


Solution

  • You can fix it easily ^^

    typescript

    editItem(item: any){
      item.editable = true;
    }
    

    html

    <ul>
      <li *ngFor="let item of items | async">
        <div class="item">
          <div class="title"> {{ item.item_title }}</div>
          <input #newItemName type="text" [(ngModel)]="this.item.item_title" *ngIf="item.editable"/>
          <i aria-hidden="true" (click)="editItem(item)"></i>
         </div>
      </li>
    </ul>