【问题标题】:Angular Reactive form Validation for dynamic forms inside *ngFor*ngFor 中动态表单的 Angular 反应式表单验证
【发布时间】:2019-02-15 10:23:15
【问题描述】:

当我试图将表单验证放到文本字段中时,我是 Angular 的新手,表单存在于 *ngFor 循环中,所以验证有效,但它显示给每个字段,但我只想验证特定字段,所以请帮助我如何将验证放入特定的表单字段。

**HTML** 

    <div class="container" *ngFor="let post of posts; let i = index">
    <div class="row">
            <div class="col-md-12" style="display: block; ">

              <form [formGroup]="commentForm" method="post" enctype="multipart/form-data" (ngSubmit)="comment_Submit(post.user_id, post.post_id,
                commentForm)">
                <div class="form-group">
                  <input type="text" class="form-control" name="comment{{i}}" formControlName="comment" id="comment"
                    placeholder="Enter comments" cols="40" rows="5" spellcheck="true"
                    style="width:100%; height: auto; border: 1px solid #ada5a5; border-radius: 4px; outline: none; user-select: text; white-space: pre-wrap; overflow-wrap: break-word; "
                    [ngClass]="{'form-control': true,
                  'is-invalid': !f.comment.valid,
                  'is-valid':f.comment.valid}">
                  <div *ngIf="f.comment.errors?.minlength && f.comment.touched" class="text-danger">Comment
                    should be at
                    least 2 characters.</div>
                </div>

                <button type="submit" class="btn-sm btn-success" [disabled]="!commentForm.valid">Comment</button>

              </form>
            </div>
          </div>
    </div>

**TypeScript**
export class PostsComponent implements OnInit {

get f() { return this.commentForm.controls; }

constructor(private userService: UserService, private formBuilder: FormBuilder,
    private alerts: AlertsService) {
   this.commentFormValidation();

  }

commentForm: FormGroup;
  ngOnInit() {   }

    commentFormValidation() {
     this.commentForm = this.formBuilder.group({
      comment: [null, [Validators.required, Validators.minLength(2)]]
    });
  }

【问题讨论】:

  • 创建 stackblitz 并分享以帮助您。您可以使用 FormArray 解决这种情况
  • 要检查是否有效的“评论,你必须使用:commentForm.controls.coment.valid,无论如何,当一个字段无效时,Angular会为你添加类,请参阅angular.io/guide/form-validation#control-status-css-classes
  • 感谢您的回复,但我正在寻找 *ngFor 循环内的表单验证迭代
  • 你想要的是FormArray。只是看起来有点奇怪。您可能希望将 posts 数组 inside 放在表单组中,而不是尝试迭代您的数组并为每个数组粘贴一个表单。
  • 在这里查看我的答案,它应该对你有帮助:stackoverflow.com/a/42975138/6294072

标签: node.js angular forms validation ngfor


【解决方案1】:

您的posts 都共享一个相同的表单。如果您有n 数量的posts,您需要n 数量的表格。我们可以通过创建一个表单组数组(只是一个 JS 数组)来实现这一点,长度与您的 posts 数组的长度相同......

formsArr = [];

constructor(private fb: FormBuilder) { }

ngOnInit() {
  this.posts.forEach((x) => {
    this.formsArr.push(this.fb.group({
      comment: this.fb.control('', [Validators.required, Validators.minLength(2)])
    }))
  })
}

然后在您的模板中迭代formsArr。您可能需要访问 posts 数组中的某些内容...所以我们在迭代中添加索引,因此您可以使用 posts[i] 访问特定的 post。同时从您的表单中删除 method="post"

<div *ngFor="let a of formsArr; let i = index">
  <form [formGroup]="a" (ngSubmit)="onSubmit(a.value, posts[i].user_id)">
    <input formControlName="comment" />
    <small *ngIf="a.hasError('minlength', 'comment') && a.get('comment').touched">
      Needs to be 2 letters
    </small>
    <button type="submit" [disabled]="!a.valid">Comment</button>
  </form>
</div>

StackBlitz

【讨论】:

  • 先生,请检查一下我的 TypeScript 代码我的 github 链接github.com/sivasankarchimata/…
  • 当我使用数据库中的 this.posts 数组时出现这样的错误,ProfileComponent.html:54 错误类型错误:无法读取 PostsComponent.push../src/app/ 处未定义的属性 'forEach' user/posts/posts.component.ts.PostsComponent.ngOnInit (posts.component.ts:70) 在 checkAndUpdateDirectiveInline (core.js:9250) 在 checkAndUpdateNodeInline (core.js:10514) 在 checkAndUpdateNode (core.js:10476)
  • 显然this.postsundefined。您需要在订阅回调中进行迭代,因为 http-request 是异步的:stackoverflow.com/questions/43055706/…
  • 我不明白你的意思。如果您的代码有问题,请分叉我的 stackblitz 并重现该问题。上面是一个演示,只是展示了你应该怎么做。如果您的帖子是异步传入的,则需要在 帖子实际有价值时执行上述代码。
  • github.com/sivasankarchimata/… 这是我的 github 源文件链接
猜你喜欢
  • 2019-05-04
  • 2019-06-17
  • 2020-12-05
  • 1970-01-01
  • 2020-04-03
  • 2020-09-07
  • 1970-01-01
相关资源
最近更新 更多