【问题标题】:Multiple form binding with the same reactive form control using *ngFor validation issue使用 *ngFor 验证问题具有相同反应式表单控件的多个表单绑定
【发布时间】:2020-04-28 17:58:54
【问题描述】:

我正在尝试制作一个博客网站评论系统。博客文章有一个评论表单字段,每个评论都有一个回复表单字段。但是回复表单和评论表单具有相同的输入字段,所以我试图用相同的反应表单初始化评论表单和回复表单。看起来像这样:

 ngOnInit(){
    this.commentForm = this.formBuilder.group({
        comment: ['', [Validators.required]]
    });
 }

我的 Html 代码如下所示:

<div *ngFor="let item of allBlogPost">
<p>item.blogPostText</p>
<div class='comment'>
    <div *ngFor="let comment of allBlogPost.comments">
        <p>{{comment.comment_text}}</p>
        <div *ngFor="let reply of comment.replies">
            <p>{{reply.reply_text}}</p>
        </div>
        <form [formGroup]="commentForm" (ngSubmit)="onReplySubmit()">
            <input type="text" formControlName="comment"/>
            <button type="submit" [disabled]="commentForm.invalid">Reply</button>
        </form>
    </div>
    <form [formGroup]="commentForm" (ngSubmit)="onCommentSubmit()">
        <input type="text" formControlName="comment"/>
        <button type="submit" [disabled]="commentForm.invalid">Comment</button>
    </form>
</div>

每当我发布 cmets 和回复时,代码都可以正常工作。但问题是当我在评论表单或回复表单中写评论时,提交按钮被激活,因为表单现在有效。但是所有其他表单提交按钮也被激活(正如我假设它正在发生的一个表单正在验证),尽管它们保持不变。但是现在我不知道如何解决这个问题。

当特定表单有效时,我需要激活特定的提交按钮。如何以角度方式获得功能?

【问题讨论】:

    标签: javascript html angular forms web


    【解决方案1】:

    有几种方法。一种方法是为您的应用制作评论组件。这将确保您拥有更多 formGroup 实例

    <div *ngFor="let item of allBlogPost">
    <p>item.blogPostText</p>
    
    <div class='comment'>
      <app-comment *ngFor="let comment of allBlogPost.comments" [comment]="comment">
      </app-comment>
    </div>
    

    像这样在你的新评论组件中使用 @Input 装饰器

    comment.component.ts

    @Component({
      selector: 'app-comment',
      templateUrl: './comment.component.html'
    })
    export class CommentComponent implements OnInit {
    @Input() comment;
    
    ngOnInit(){
      this.commentForm = this.formBuilder.group({
        comment: ['', [Validators.required]]
      });
    }
    
    // Remember to move the rest of the comment logic from your bloglist...
    
    }
    
    

    comment.component.html

    <p>{{comment.comment_text}}</p>
    <div *ngFor="let reply of comment.replies">
      <p>{{reply.reply_text}}</p>
    </div>
    <form [formGroup]="commentForm" (ngSubmit)="onReplySubmit()">
      <input type="text" formControlName="comment"/>
      <button type="submit" [disabled]="commentForm.invalid">Reply</button>
    </form>
    </div>
    <form [formGroup]="commentForm" (ngSubmit)="onCommentSubmit()">
      <input type="text" formControlName="comment"/>
      <button type="submit" [disabled]="commentForm.invalid">Comment</button>
    </form>
    

    【讨论】:

    • 我尝试了其他方法,因为我不想从该组件中移动业务逻辑,但所有方法都让我失败了。但是这种方法对我有用。毕竟谢谢。
    猜你喜欢
    • 2017-05-28
    • 1970-01-01
    • 2018-09-29
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多