Robert
Robert

Reputation: 2691

Angular ngIf with dynamic generated property

I have app in Angular and in html I have list of posts. Under every post I want to have textarea to add new comment. I want to show/hide this textarea after click button. But I can't do ngIf="someproperty" because after click button all textareas will be shown.

<a href="" (click)="enabledAddComment = true"></a>

<div>
  <div *ngIf="enabledAddComment" class="p-2 form-group">
    <textarea type="text" class="form-control" id="inputCommentBody" placeholder="Text" [(ngModel)]="postCommentModel.body" rows="3"></textarea>
  </div>
  <button>
    Add comment
  </button>
</div>

I want to add to property enabledAddComment postId but how to add postId in typescript file?:

 public enabledAddComment: boolean;

Upvotes: 1

Views: 2045

Answers (2)

Avinash Dalvi
Avinash Dalvi

Reputation: 9301

You pass post $index in function to enable particular post text area.

<a href="" (click)="enabledAddComment($index)"></a>

<div>
              <div *ngIf="postCommentModel.enableAddCommentText" class="p-2 form-group">
                <textarea type="text" class="form-control" id="inputCommentBody" placeholder="Text" [(ngModel)]="postCommentModel.body" rows="3"></textarea>
              </div>
              <button>
                Add comment
              </button>
            </div>

function enableAddComment(index){
if (this.post[index].enableAddCommentText == false)
 {
  this.post[index].enableAddCommentText = true;
 }
else{
this.post[index].enableAddCommentText = false;
}
}

Upvotes: 0

Arun Mohan
Arun Mohan

Reputation: 1227

Use the postCommentModel itself. Add a isSelected flag to toggle ngIf condition.

Upvotes: 1

Related Questions