简体   繁体   中英

How can I access or check validation of the child component's template driven form in the super parent's component

Say i am having a set of components with the parent-child relationship. The the structure is as follows: [A]-->[B]-->[C]-->[D] (ie) A is the parent of B , B is the parent of C , C is the parent of D. I need to check the validity of template-driven form in component D from the component A . I have tried using @viewchild(). in my componentA.html

 <form #mainform ="ngform"> <button [disabled]= "componentB?.ComponentC?.ComponentD?.form?.invalid"> </button> </form> 

This approach is not working.

How can I achieve this from A to D without using event emitter?

It does not matter how deeply it is nested in the component tree. It matters how it is nested in the form tree.

Asumming the child controls are named child , grandchild and grandgrandchild you can do something like this:

<form #mainform="ngform">
  <button [disabled]="mainform.control.get('child.grandchild.grandgrandchild').invalid">
    </button>
</form>

We use the mainform.control to get the access to the underlying FormGroup . Now we have an access to all methods on the FormGroup class. You can see the full list here .

Next we use the get method to traverse the form tree and reach for the child control.

If you have a form tree like this:

mainform: {
  child: {
    grandchild: {
       grandChild
    }
  }
}

Where mainform , child , and grandchild are FromGroups and grandgrandchild is a FormControl`.

You can access the grandgrandchild by typing: mainForm.get('child.grandchild.grandchild')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM