1 year ago

#377780

test-img

David Wolf

Angular reactive FormGroups loop

The goal is to have a dynamic component to automatically render required error messages for a given reactive form.

.component.html

        <ng-template #errTpl let-control>
            <div *ngIf="control.value?.invalid && (control.value?.dirty || control.value?.touched)">
                <div *ngIf="control.value?.errors?.['required']" class="alert alert-danger">
                    {{ control.key | titlecase }} is required
                </div>
            </div>
        </ng-template>

        <div *ngFor="let control of signUpForm.controls | keyvalue">
                <div *ngIf="isFormGroup(signUpForm.get(control.key)); else elseBlock">
                    <!-- How to loop over controls? -->
                    <div *ngIf="signUpForm.get(control.key)['controls'] !== null">
                        ...
                    </div>
                </div>
                <ng-template #elseBlock>
                    <ng-container [ngTemplateOutlet]="errTpl" [ngTemplateOutletContext]="{ $implicit: control }">
                    </ng-container>
                </ng-template>
        </div>

Works fine when the form only has FormControls, to handle FormGroups, the following method is added to the component and used in the *ngIf above, to check what is handled.

.component.ts

  isFormGroup(candidate: any) {
    return candidate instanceof FormGroup
  }

However, looping over the FormGroup controls, isn't working as desired.

Accessing:

signUpForm.get(control.key)['controls']

Ends up in:

TS2531: Object is possibly 'null'.

Even when wrapping the accessing into a conditional block, the same error message appears.

<div *ngIf="signUpForm.get(control.key)['controls'] !== null">
    ...
</div>

How should the controls be accessed, to be able to pass them to the template in a loop.

Or is there even a better way to apply standard error messages without hardcoding each error message block, and without having to loop over each control?

Additional ways to access the child controls (EDIT)

signUpForm.get(control.key)!.controls

throws

TS2339: Property 'controls' does not exist on type 'AbstractControl'.

signUpForm.get(control.key)!['controls']

throws:

TS7052: Element implicitly has an 'any' type because type 'AbstractControl' has no index signature. Did you mean to call 'get'?

Using .get() returns null again.


<div *ngFor="let childControl of control.value!.value | keyvalue">
    {{childControl.value?.error}}

Using the above works to get the childControl, but trying to get the erros ends up in:

TS2571: Object is of type 'unknown'.

angular

angular-reactive-forms

angular-forms

angular-template

0 Answers

Your Answer

Accepted video resources