首页 > 解决方案 > 如何设置表单控件值如果表单控件值在反应式表单方法中的 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])
    });

标签: angular

解决方案


您可以通过 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> 


推荐阅读