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

相关内容

热门资讯

四分钟辅助!wpk辅助,epo... 四分钟辅助!wpk辅助,epoker透视,机巧教程(有挂方式)1、下载好epoker透视透视辅助下载...
1分钟辅助!红龙poker辅助... 1分钟辅助!红龙poker辅助器免费观看,微扑克微乐辅助,诀窍教程(今日头条)1、在红龙poker辅...
9分钟辅助!佛手在线大菠萝智能... 9分钟辅助!佛手在线大菠萝智能辅助器,wpk有那种辅助吗,积累教程(确实有挂)1、佛手在线大菠萝智能...
4分钟辅助!hhpoker视频... 4分钟辅助!hhpoker视频巡查真的假的,aa poker辅助包,步骤教程(有挂技巧)hhpoke...
六分钟辅助!约局吧德州可以透视... 六分钟辅助!约局吧德州可以透视吗,拱趴游戏破解器,技法教程(有挂实锤)1、每一步都需要思考,不同水平...
第5分钟辅助!pokemmo内... 第5分钟辅助!pokemmo内置修改器,werplan外卦神器,方针教程(有挂详细)1)pokemm...
九分钟辅助!wepoker高级... 九分钟辅助!wepoker高级辅助,hh poker软件,机巧教程(有人有挂)1、下载好wepoke...
第十分钟辅助!wepoker透... 第十分钟辅助!wepoker透视脚本免费下载,约局吧作弊脚本,操作教程(有挂秘籍)1、全新机制【we...
4分钟辅助!wepoker透视... 4分钟辅助!wepoker透视脚本免费,pokemmo手机脚本,讲义教程(揭秘有挂)wepoker透...
第九分钟辅助!newpoker... 第九分钟辅助!newpoker怎么安装脚本,pokemmo手机辅助软件,方案教程(有挂技巧)1、该软...