Search code examples
javascriptangulartypescriptdisabled-input

Disabled element by given id - typescript angular


I need yours help. It is possible when a have list of comments as textareas and i would like to disabled single element (comment) by given this element id. Whati have:

<div style="float: right">
    <button mat-button color="primary">
        <mat-icon class="md-24" (click)="edit()" >edit</mat-icon>
    </button>
     <textarea [disabled]='enableTextarea' class="comment-textarea" matInput cdkTextareaAutosize rows="2">{{comment.content}}</textarea>       
</div>

{{coment.content}} - is content of the comment and it is it what i want to edit (it means enable)

export class CommentComponent implements OnInit {

enableTextarea = true;

edit() {
    this.enableTextarea = !this.enableTextarea;
  }

}

Here i have two coments with id 1 and 2, and what he wants to achieve to be able to after click edit (pencil on right) disable single comments. In my code all comments are edited, no matter who clicks.


Solution

  • You need to change enableTextarea from boolean to boolean[]. That way each item will be independent of the other

    In your component

    
    enableTextarea = [false];
    
    edit(i) {
      this.enableTextarea[i] = !this.enableTextarea[i];
    }
    
    

    Now in your html,

    1. Change the loop by adding index
        <div *ngFor="let comment of comments; let i = index">
    
           <!-- Other Contents Here -->
        </div>
    
    1. change all enableTextarea to enableTextarea[i]

    2. Change edit() to edit(i)

                    <div *ngFor="let comment of comments; let i = index">
                        <div>
                            {{comment.createDate }}
                            <div style="float: right">
                                <button mat-button color="primary" (click)="deleteComment(comment.id)">
                    <mat-icon class="md-24">delete</mat-icon>
                  </button>
                                <button mat-button color="primary">
                    <mat-icon class="md-24" (click)="edit(i)">edit</mat-icon>
                  </button>
                            </div>
                        </div>
                        <div *ngIf="enableTextarea[i] == false">
                            <h5 class="h5-edited">editing</h5>
                        </div>
                        <textarea [disabled]='enableTextarea[i]' class="comment-textarea" matInput cdkTextareaAutosize
                        rows="2">{{comment.content}}</textarea>
                        <button mat-button color="primary" *ngIf="enableTextarea[i] == false" (click)="updateComment(comment.id)">Save
              </button>
                        <br><br><br>
            </div>
    

    See Demo Here