I have created a form (in the parent), with 2 inputs, one in each child component ( each component is in a ngbootstrap tab). I pass the formgroup to each child component and I add the validators to the formgroup in the ngOnInit of each component.
I discovered that ngOnInit of each component is only run AFTER I click to view the tab. That means that the overall form's validity cannot be determined until AFTER I view each tab (in case an input starts in an invalid state).
What is the correct way to handle this? Since the formcomponents aren't created until after the tab is viewed I can't add validators in the parent.
I ran into this same thing. In my case, I decided to handle the validation directly in addition to the built-in validators.
The built-in validators provide the user with immediately feedback when they are on a particular tab. My validation code then keeps track of the overall validity of the data model.
My code is here: https://github.com/DeborahK/Angular-Routing Check out the
APM-Final
folder.I was then able to add an icon on any tab that has a validation error like this:
My validate method looks like this:
Where dataIsValid is a set of key and value pairs defining the name of each tab and true if its contents is valid, otherwise false.
This requires then some duplicated code (code here matches the validators in the HTML) ... but this seems necessary until Angular provides some data focused validation features instead of just form/component-based validation.
NOTE: This example uses template-driven forms but you could use something similar for reactive forms.