Search code examples
htmlangularlistdrop-down-menung-template

How to edit a textinput within a list


I have a list of comment boxes and buttons that go with each box. When the user clicks edit I only want that particular textbox to be enabled. When the click save or cancel I want the text box to be hidden and the "

" to be visible.

Here is my ng-template where I am trying to track by index

         <ng-template #item let-item let-i="index">
           <textarea [disabled]="IsDisabled(i)" [(ngModel)]="item.commentText" nz-input rows="4"></textarea>
             <nz-form-item>
              <button nz-button nzType="primary" [nzLoading]="submitting" (click)="openEdit(i)">Edit Comment</button>
               <button (click)=updateCommentsById(item, index)>                                    
                Save Comment</button>
              </nz-form-item>
              </nz-form-item>
           </ng-template>



async updateCommentsById(item, index) {
        console.log(item, index);

}
openEdit(index){
//Open this list item for edit
}

 IsDisabled(index, disableMe = true) {
    return disableMe;
}

editCommentClicked(index) {
    this.IsDisabled(index, false);
}

cancelCommentClicked(index) {
    this.IsDisabled(index, true);
}

As you see in this list each row has a textarea. When the user clicks on the Edit button I want the textbox to be enabled for that row only. When the user clicks cancel or Save I want the corresponding actions to be attached for that row only.

How can I use the index to edit and save each row


Solution

  • What you want to do here is add an element id and append the index to the element id

    <ng-template #item let-item let-i="index">
               <textarea id="TextComment_{{index}}" [disabled]="IsDisabled(i)" [(ngModel)]="item.commentText" nz-input rows="4"></textarea>
                 <nz-form-item>
                  <button id="EditComment_{{index}}" nz-button nzType="primary" [nzLoading]="submitting" (click)="openEdit(i)">Edit Comment</button>
                   <button id="SaveComment_{{index}}" (click)=updateCommentsById(item, index)>                                    
                    Save Comment</button>
                  </nz-form-item>
                  </nz-form-item>
               </ng-template>
    

    then on your button clicks you can expose your elements from the dom based on the id name

    onClick(){
      (document.getElementById('EditComment_' + index) as any).disabled = true;
            (document.getElementById('CancelButton_' + index) as any).disabled = false;
            (document.getElementById('TextComment_' + index) as any).disabled = false;
            (document.getElementById('SaveComment_' + index) as any).disabled = false;
    }