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方法中,遍历子表单的所有控件,并将其标记为'已触摸”并更新其值和有效性状态。

相关内容

热门资讯

德扑之心免费透视!pokemm... 德扑之心免费透视!pokemmo手机辅助软件(透视)技巧-确实解谜真的有挂1、操作简单,无需poke...
透视普及!哈糖大菠萝能开挂吗(... 透视普及!哈糖大菠萝能开挂吗(透视)agpoker辅助,教程练习(有挂分享)-哔哩哔哩1、下载好哈糖...
wejoker免费脚本!xpo... wejoker免费脚本!xpoker透视辅助(透视)器-都是教你有挂1、wejoker免费脚本模拟器...
透视曝光!hhpoker怎么开... 透视曝光!hhpoker怎么开透视(透视)德普之星透视辅助软件是真的吗,教程绝活(有挂攻略)-哔哩哔...
wepoker有没有机器人!w... wepoker有没有机器人!wepoker有用吗(透视)脚本-果然了解是真的挂1、打开软件启动之后找...
透视专业!德州圈脚本(透视)红... 透视专业!德州圈脚本(透视)红龙poker辅助,教程项目(有挂方式)-哔哩哔哩运红龙poker辅助辅...
uupoker透视!wepok... uupoker透视!wepoker是不是有人用挂(透视)攻略-竟然有挂真的有挂1)wepoker是不...
透视有挂!wpk有辅助器吗(透... 透视有挂!wpk有辅助器吗(透视)wepoker私局辅助,教程机巧(有挂功能)-哔哩哔哩1、金币登录...
wepokerplus脚本!p... wepokerplus脚本!pokemmo手机版脚本免费(透视)方法-其实推荐存在有挂1、pokem...
透视辅助!德普之星辅助工具如何... 透视辅助!德普之星辅助工具如何设置(透视)hhpoker免费辅助器,教程讲义(有挂存在)-哔哩哔哩1...