MegaTron
MegaTron

Reputation: 3393

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 :)

Upvotes: 3

Views: 6799

Answers (2)

coturiv
coturiv

Reputation: 2970

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>

Upvotes: 4

Iancovici
Iancovici

Reputation: 5731

You can.. create an editMode boolean, and array of editStates booleans (one for each item) in component.ts

editMode = false;
editable = new Array<boolean>(this.items.length);

Then convert function to set all to false, and edit

  • on click event: editItem, feed it the index (so in your ngFor loop add let i = index) item, and set use quick false fill array followed by index of choice to true.

  • on hoverout exit event: exitEditMode.


  editItem(index: number) {
    this.editMode = true;
    this.editable.fill(false);
    this.editable[index] = true;
  }

  exitEditMode() {
    this.editMode = false;
  }

Then in the html, you can use ngIf to hide all editables that are disabled in edit mode, by probing for editMode and editable selected. Something like this:

<ul>
  <li *ngFor="let item of items | async; let i = index">
    <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" *ngIf="editMode && editable[i]" (click)="editItem(i)" (mouseout)="exitEditMode()"></i>
    </div>
  </li>
</ul>

Upvotes: 1

Related Questions