Search code examples
angularngforangular-ng-if

How to display an element specific to an object in an array with ngIf


I am trying to allow the end user the ability to edit a post they have created. I am displaying an array of posts to them using Angular ngFor. The content of the post has an ngIf which is toggled if the user wants to edit the post.

<div class="card-body">
  <p class="card-text" *ngIf="!showEditPost">{{ post.content }}</p>
  <div *ngIf="showEditPost">
    <div class="row" >
      <div class="col-md-12">
        <textarea name="text-post" [(ngModel)]="post.content" class="form-control" rows="3"></textarea>
      </div>
    </div>
    <div class="row mt-2">
      <div class="col-md-12">
        <button class="btn btn-light">Cancel</button>
        <button class="btn btn-primary" (click)="updatePost()">Save</button>
      </div>
    </div>
  </div>
</div>

The problem I am having is that the showEditPost variable is the same on every iteration of the ngFor array, which means that every single post will be editable when showEditPost is true.

My question is how do I edit a specific post without making every post editable at the same time.

Thanks in advance :)


Solution

  • In that case you need to add a property named showEdit on each post object and then you can just do

    <p class="card-text" *ngIf="!post.showEdit">{{ post.content }}</p>