【问题标题】:Angular 2 - Mark nested formbuilder as TouchedAngular 2 - 将嵌套的表单构建器标记为已触及
【发布时间】:2017-09-18 23:00:35
【问题描述】:

我有以下问题:在我的应用程序中,我有一个巨大的表单,其中包含嵌套的表单构建器,它工作得很好,但当用户提交表单时,我想将完整表单标记为已触摸(以运行验证),代码是

constructor(private fb: FormBuilder) {
    this.form= fb.group({
        field1: [null],
        field2: [null],
        nestedForm1: fb.group({
            field3: [null, Validators.required],
            field4: [null]
        }),
        nestedForm2: fb.group({
            field5: [null, Validators.required],
            field6: [null, Validators.required]
        })
    });
}

当我跑步时:

this.form.markAsTouched();

只有 Field1 和 Field2 被标记,有没有我想念的方法?

【问题讨论】:

    标签: forms nested angular2-forms formbuilder


    【解决方案1】:

    您可以创建如下自定义方法:

     setAsTouched(group: FormGroup | FormArray) {
      group.markAsTouched()
      for (let i in group.controls) {
        if (group.controls[i] instanceof FormControl) {
          group.controls[i].markAsTouched();
        } else {
          this.setAsTouched(group.controls[i]);
        }
       }
     }
    

    【讨论】:

    • 谢谢!这正是我正在寻找的,我无法投票,但我将您的答案标记为已接受,真的非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 2016-09-18
    • 2018-02-21
    相关资源
    最近更新 更多