Angular2 show all form group validation errors

I am creating a deep nested form with Angular2 and FormGroup, currently I have a form, for example in the parent controller:

this.orderForm = this.fb.group({

customerSelectForm: this.fb.group({ // create nested formgroup to pass to child
        selectTypeahead: ['', 
                            Validators.required],
        })
})

Then in the child component I:

<div class="form-group" [formGroup]="customerSelectForm" *ngIf="customerSelectForm">
        <label for="oh-custaccount">Customer Account #</label>

    <input class="form-control" type="text" 
    formControlName="selectTypeahead"
    (focusout)=someFunction() />

    <p *ngIf="customerSelectForm.controls.selectTypeahead.errors?.required">
    Number required!</p>
</div>

Now this child template works fine and displays an error on the screen if there is no input in the text box. Then I return to the parent controller with the submit button:

<button type="submit" class=" btn btn-success" [disabled]="orderForm?.invalid">Submit</button>

Again, this works as expected, and only gets activated after the input is registered in the selectTypeahead element.

Now, due to the large nature of this form, I want to have a display next to the submit button, which lists all the form elements that currently do not work. I tried to render:

{{orderForm.errors}}

"null", , orderFrom, / ?

+6
1

, , .

getAllErrors(form: FormGroup | FormArray): { [key: string]: any; } | null {
    let hasError = false;
    const result = Object.keys(form.controls).reduce((acc, key) => {
        const control = form.get(key);
        const errors = (control instanceof FormGroup || control instanceof FormArray)
            ? this.getAllErrors(control)
            : control.errors;
        if (errors) {
            acc[key] = errors;
            hasError = true;
        }
        return acc;
    }, {} as { [key: string]: any; });
    return hasError ? result : null;
}

{{getAllErrors(orderForm)}}
+2

All Articles