Angular 2 : Validate child component form fields from the parent component

14,143

We can achieve it using template driven technique as well. Find below the steps :

  • From parent component to child component we have to pass submit button event.

    <button type="button" (click)="enterForm(parentForm)">Submit</button>
    

    Here, parentForm is the form reference.

  • call child component method using @ViewChild decorator from parent to pass submit button event on click of submit.

    @ViewChild('validateChildComponentForm') private ChildComponent: ChildComponent;
    
  • Pass the reference of child form using @ViewChild decorator into the child component.

    @ViewChild('smartyStreetForm') form;
    
    enterForm(parentForm) {
        this.submitted = true;
        this.ChildComponent.validateChildForm(this.submitted);
        if(!parentForm.valid || !this.childFormValidCheck) {
            return;
        } else {
           // success code comes here.
        }                
    }
    
  • Now in child component method we will check that if parent form is submitted and child component form is valid then emit true otherwise false into the parent component. we will use @Output decorator to emit the isChildFormValid value into the parent component.

    @Output() isChildFormValid: EventEmitter<any> = new EventEmitter<any>();
    
    public validateChildForm(data: any) {
        if (data === true) {
            if(this.form.valid === true) {
                this.isChildFormValid.emit(true);
            } else {
                this.isChildFormValid.emit(false);
            }
        }
    } 
    
  • Now in parent component we will get the isChildFormValid value.

    private isChildFormValid(formValid: any) {
        this.childFormValidCheck = formValid;
    }
    

Pictorial representation :

enter image description here

Share:
14,143

Related videos on Youtube

Rohìt Jíndal
Author by

Rohìt Jíndal

Life is a series of problems. Do we want to moan about them or solve them ? - M. Scott Peck I'm a software engineer with a particular interest in web technologies (JavaScript, TypeScript, JavaScript frameworks/libraries). I am also learning and getting hands on in Python and AWS server less services. I've been doing this professionally for over 8 years. I love the challenge of helping other developers to resolve and overcome their hurdles, and expanding my own knowledge base at the same time. Outside of the techie stuff, I love to do explore different places (travelling/hiking/trekking) and cultures. If you would like to thank me, you can buy me a coffee :)

Updated on June 04, 2022

Comments