2

I Have forms like this, in parent i am including multiple child components each child component is formgroup. now i need to check all this child forms validation on parent form when user click OnSubmit.

How should i trigger child form validations from parent on submit. I have used FormBuilder in each childcomponent.

I am able to do validation when user click on child fields but if user doesn't enter anything or touched anything and try to submit validations not showing errors.

parent.component.html

<form> <child1></child1> <child2></child2> <child3></child4> <child4></child4> '''' '''' '''' </form> 

child1.component.html

<div formgroup="child1group"> <div formarray= "child1array"> .... ... ... </div> </div 

child2.component.html

<div formgroup="child2group"> <div formarray= "child2array"> .... ... ... </div> </div 

please someone tell me how to do this validation on angular 4 ?

1 Answer 1

-1

Pass the Formcontrol to Parent as OUTPUT and then do validation by calling function SaveConsole() in button click

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); } }); } 
Sign up to request clarification or add additional context in comments.

1 Comment

if I have 20 child component then I have to check 20 times the validation of those controllers in SaveConsole().. this is a bad approach imho

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.