Search code examples
angularcommunication

Angular Parent Child - Pass data to child component


Our angular application is basically a small workflow with previous and back buttons.

We have created a component (for Back & Previous) and used them in all the reactive forms. The parent component/forms accept input data (table is displayed) from the user and it needs to be validated before the form is submitted. A user also cannot navigate if there does not exist a single entry in the table.

The question is how can the child component know about the form being valid or not?

Approach: Have a variable isvalid = false when component is initialized and if there are rows set it to true. Now if user deletes all rows again set to false. Is there a better approach rather than the one stated above as the variable will have to be managed for all events in the form?


Solution

  • Reactive forms in angular comes with a property invalid which returns true if form is invalid and false if valid.

    You can pass this property to the child and use it in your child components as per your requirement. In this way you do not have overhead of managing a variable as the property will automatically set depend on form validation.

    <app-child-component [isParentInvalid]="ParentForm.invalid">
    

    Where app-child-component must have a property:

     @Input() isParentInvalid: boolean;