我有这样的表单,在父级中,我包含多个子组件,每个子组件都是表单组。现在,当用户单击OnSubmit时,我需要检查父窗体上的所有子窗体验证。
如何在提交时触发来自父母的子表单验证。我在每个子组件中都使用了FormBuilder。
当用户单击子字段时,我可以进行验证,但如果用户没有输入任何内容或触摸任何内容,并尝试提交没有显示错误的验证。
parent.component.html
<form>
<child1></child1>
<child2></child2>
<child3></child4>
<child4></child4>
''''
''''
''''
</form>child1.component.html
<div formgroup="child1group">
<div formarray= "child1array">
....
...
...
</div>
</divchild2.component.html
<div formgroup="child2group">
<div formarray= "child2array">
....
...
...
</div>
</div请有人告诉我如何在角4上做这个验证?
发布于 2017-11-14 09:39:19
将窗体控件作为输出传递给父控件,然后按一下按钮调用函数SaveConsole()进行验证
child1.component.ts
@Output() public childControls = new EventEmitter();
public ngOnInit() {
this.childControls.emit(this.child1group);
this.child1group.valueChanges.subscribe(() => {
this.childControls.emit(this.child1group);
});
}parent.component.html
<form>
<child1 (childControls)="child1Control = $event"></child1>
<button (Click)=SaveConsole()> Submit </butto>
</form>parent.ts
public child1Control: FormGroup;
public SaveConsole() {
if (this.child1Control.valid) {
// SAVE FORM
} else {
this.validateAllFormFields(this.child1Control);
}
}
public validateAllFormFields(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
} else if (control instanceof FormGroup) {
this.validateAllFormFields(control);
}
});
}https://stackoverflow.com/questions/47279252
复制相似问题