angular - 如何设置表单控件值如果表单控件值在反应式表单方法中的 ngFor 循环内,
问题描述
我正在尝试制作类似 facebook 的东西,现在我被卡住了,因为我想在每个帖子上都有评论表单,以便用户可以对每个帖子发表评论,但由于这个原因,我必须确定提交了哪个帖子的评论表单,为此目的我使用带有 postId 作为值的隐藏输入但是当我分配表单控件时,我为表单控件分配了空值,因为我不知道值是什么,这是现在的主要问题.. 我的模板中有数据但是我想在 formControls 中动态分配该数据,并坚持反应式表单方法。
这是我的代码:
<article class="post" *ngFor="let post of posts">
<div class="post-body">
<div class="post-content">
{{ post.content }}
</div>
<div class="comment-area">
<form class="comment-form" [formGroup]="commentForm" (ngSubmit)="onComment()">
<img class="profile-pic" src="../../assets/profile.jpg">
<input type="text" class="comment-input" formControlName="comment">
<!-- Here is issue, value is inside post._id -->
<input type="hidden" [value]="post._id" formControlName="postId">
<button type="submit" class="comment-sub">Send</button>
</form>
</div>
</div>
</article>
TS代码:
commentForm = new FormGroup({
comment: new FormControl('', [PostValidator.notEmpty]),
postId: new FormControl('', [Validators.required])
});
解决方案
您可以通过 PostId 点击提交,您将获得功能,然后您可以保存它
<article class="post" *ngFor="let post of posts">
<div class="post-body">
<div class="post-content">
{{ post.content }}
</div>
<div class="comment-area">
<form class="comment-form" [formGroup]="commentForm" (ngSubmit)="onComment(post._id)">
<img class="profile-pic" src="../../assets/profile.jpg">
<input type="text" class="comment-input" formControlName="comment">
<button type="submit" class="comment-sub">Send</button>
</div>
</div>
推荐阅读
- cmake - 如何安装 protobuf 并链接到 cmake?
- django - 当我尝试将数据传递给表单时,“WSGIRequest”对象没有属性“get”
- python - 使用 scipy.minimize_scalar 时,numpy.ndarray lambda 不能在循环内调用,单次运行效果很好
- python - 如何同时使用键盘和鼠标控制器
- docker - Spring Cloud Data Flow 安全配置和与 RedHat SSO 的集成
- pki - 我无法从 EJBCA 社区版中提取私钥 - PrivateKeyNotExtractableException
- typescript - Typeorm migration:create 忽略配置中的 migrationsDir
- firebase - firebase 规则:获取集合的所有 id
- ffmpeg - 使用 libav 混合可流式分段 mp4
- java - 登录后 Spring-webflow SnapshotCreationException 错误