How to set form control value If formcontrol value

2019-09-19 20:25发布

问题:

I am trying to make something like facebook, Now I am stuck because I want to have comment form on each post so that user can comment on every post, But due to this I have to identify which post's comment form is submitted, For this purpose I used hidden input with postId as value But when I assign form control, I assign form control with empty value because I don't have any clue what would be the value, this is main issue Now.. I have data in my template But I want to assign that data in formControls dynamically sticking to reactive form approach.

Here is my code:

<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 code:

commentForm = new FormGroup({
        comment: new FormControl('', [PostValidator.notEmpty]),
        postId: new FormControl('', [Validators.required])
    });

回答1:

You can Pass PostId On click of Submit which you will get on function And then you can Save it

<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> 



标签: angular