I have the following HTML structure:
<div *ngFor="let post of posts">
<div>{{post.description}}</div>
<ul *ngFor="let comment of post.comments">
<li>
{{comment.description}}
</li>
</ul>
<div>
<textarea placeholder="leave your comments here"></textarea>
<button (click)="addComment(post)">Save</button>
</div>
</div>
Considering it will contains a lot of posts on the page, how can I add dynamically a new comment to the specific post I am writing?
I would suggest to make a post component containing also a struktur (like array) holding your comments. Then apply *ngFor with your new component.
Maybe something like this: https://stackblitz.com/edit/angular-b9tkry
It ended like:
<ng-container *ngFor="let post of posts">
<app-post [post]="post"></app-post>
</ng-container>
And on app-post
:
<p>
{{post.text}}
</p>
<ul *ngFor="let comment of post.comments">
<li>{{comment}}</li>
</ul>
<textarea [(ngModel)]="newComment"></textarea>
<button (click)="addComment()">Add comment</button>