在子组件上手动触发验证,可以通过使用@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方法中,遍历子表单的所有控件,并将其标记为'已触摸”并更新其值和有效性状态。