Angular响应式表单在子组件上提交时无法触发验证。
创始人
2024-10-30 08:00:30
0

在子组件上手动触发验证,可以通过使用@ViewChild装饰器获取每个子组件的表单控件,并在提交钩子中手动调用其验证方法。以下是示例代码:

父组件模板:

父组件代码:

export class ParentComponent implements OnInit {
  parentForm: FormGroup;
  @ViewChild(ChildComponent) childComponent: ChildComponent;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.parentForm = this.fb.group({
      child: ['', Validators.required]
    });
  }

  onSubmit() {
    if (this.parentForm.valid && this.childComponent.childForm.valid) {
      console.log('Form submitted successfully');
    } else {
      console.log('Form submission failed');
    }
  }
}

子组件模板:

子组件代码:

export class ChildComponent {
  childForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.childForm = this.fb.group({
      name: ['', Validators.required]
    });
  }

  validate() {
    Object.values(this.childForm.controls).forEach(control => {
      control.markAsTouched();
      control.updateValueAndValidity();
    });
  }
}

在父组件中,使用@ViewChild来获取ChildComponent实例并存储在childComponent属性中。在提交钩子中,首先检查父表单是否有效,然后检查子组件的表单是否有效。如果子组件表单无效,则手动调用其validate方法以触发验证。在validate方法中,遍历子表单的所有控件,并将其标记为'已触摸”并更新其值和有效性状态。

相关内容

热门资讯

2分钟细说!佛手在线是不是有挂... 2分钟细说!佛手在线是不是有挂,wepoker透视脚本安卓,安装教程(有挂方法);1.佛手在线是不是...
查到实测!wepoker手机助... 查到实测!wepoker手机助手,拱趴大菠萝挂哪里,解说技巧(有挂技巧)准备好在拱趴大菠萝挂哪里ia...
必备教程!德普之星透视辅助,哈... 必备教程!德普之星透视辅助,哈糖大菠萝怎么挂,曝光教程(有挂软件);实战中需综合运用上述技巧,并根据...
玩家必看攻略!红龙poker辅... 玩家必看攻略!红龙poker辅助工具,pokernow辅助工具,详细教程(有挂辅助)是一款可以让一直...
推荐一款!poker worl... 推荐一款!poker world辅助,hhpkoer辅助挂是真的吗,透明挂教程(有挂神器)这是由厦门...
我来教教大家!newpoker... 我来教教大家!newpoker脚本,wepoker辅助插件功能,解说技巧(有挂神器);建议优先通过w...
信息共享!wejoker透视方... 信息共享!wejoker透视方法,hhpoker辅助挂下载,科技教程(有挂攻略);致您一封信;亲爱h...
玩家攻略!hhpoker透视脚... 玩家攻略!hhpoker透视脚本视频,hhpoker辅助软件,必备教程(有挂攻略);1分钟了解详细教...
推荐一款!aapoker如何设... 此外,数据分析德州(aapoker如何设置胜率)辅助神器app还具备辅助透视行为开挂功能,通过对客户...
如何分辨真伪!约局吧德州真的有... 如何分辨真伪!约局吧德州真的有透视挂吗,aapoker怎么拿好牌,2025新版(有挂方法)1、许多玩...