Adding reactivate validators to form with inputs in child components in tabs

721 views Asked by At

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.

1

There are 1 answers

1
DeborahK On

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:

enter image description here

My validate method looks like this:

private dataIsValid: { [key: string]: boolean } = {};

validate(): void {
    // Clear the validation object
    this.dataIsValid = {};

    // 'info' tab
    if (this.product.productName &&
        this.product.productName.length >= 3 &&
        this.product.productCode) {
        this.dataIsValid['info'] = true;
    } else {
        this.dataIsValid['info'] = false;
    }

    // 'tags' tab
    if (this.product.category &&
        this.product.category.length >= 3) {
        this.dataIsValid['tags'] = true;
    } else {
        this.dataIsValid['tags'] = false;
    }
}

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.