将特定形式添加到 *ngFor 内的项目
Add specific form to item inside *ngFor
我有以下 HTML 结构:
<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>
考虑到它会在页面上包含很多 post,我如何才能动态地向我正在写的特定 post 添加新评论?
因为您将 post 传递给 addComment 方法,您应该能够推送到相同的评论数组。
addComment(post:any){
post.comments.push(comment);
}
并将 ngModel 添加到您的模板中,
<textarea placeholder="leave your comments here" [(ngModel)]='comment'
考虑添加以下函数签名,以传递相关的 post 和 新评论:
<textarea placeholder="leave your comments here" #commentText></textarea>
<button (click)="addComment(post, commentText)">Save</button>
然后,假设评论是 post 模型的一部分,只需将新评论附加到现有评论即可:
addComment(post: any, newComment: HTMLInputElement){
post.comments.push(newComment.value);
}
我建议制作一个 post 组件,其中还包含一个保存您的评论的结构(如数组)。然后将 *ngFor 应用于您的新组件。
也许是这样的:
https://stackblitz.com/edit/angular-b9tkry
它的结尾是这样的:
<ng-container *ngFor="let post of posts">
<app-post [post]="post"></app-post>
</ng-container>
在 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>
我有以下 HTML 结构:
<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>
考虑到它会在页面上包含很多 post,我如何才能动态地向我正在写的特定 post 添加新评论?
因为您将 post 传递给 addComment 方法,您应该能够推送到相同的评论数组。
addComment(post:any){
post.comments.push(comment);
}
并将 ngModel 添加到您的模板中,
<textarea placeholder="leave your comments here" [(ngModel)]='comment'
考虑添加以下函数签名,以传递相关的 post 和 新评论:
<textarea placeholder="leave your comments here" #commentText></textarea>
<button (click)="addComment(post, commentText)">Save</button>
然后,假设评论是 post 模型的一部分,只需将新评论附加到现有评论即可:
addComment(post: any, newComment: HTMLInputElement){
post.comments.push(newComment.value);
}
我建议制作一个 post 组件,其中还包含一个保存您的评论的结构(如数组)。然后将 *ngFor 应用于您的新组件。
也许是这样的: https://stackblitz.com/edit/angular-b9tkry
它的结尾是这样的:
<ng-container *ngFor="let post of posts">
<app-post [post]="post"></app-post>
</ng-container>
在 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>