DAG
DAG

Reputation: 2630

ReactiveForms hasError('required') always returning false

In my Angular App, we have an array of inputs, for now we have the following going on:

{{ item.valid }} returns false in case the required validation was fulfilled -> That is correct

If we do: item.hasError('required') it returns false -> That is NOT correct

What do I need to make the hasError method to work?

That is how we build our Reactive Form:

private buildForm(prices: Array<Price>, arrayName: string): FormArray {
    let controls = new FormArray([]);

    prognoseAngaben.forEach(price => {
      controls.push(new FormGroup(
        {
          value: new FormControl(price.value, [Validators.required, Validators.min(0)]),
        }));
    });

    this.myForm.setControl(arrayName, controls);

    return controls;
}

And that is our HTML:

<tbody [formArrayName]="arrayName">
    <tr *ngFor="let item of myForm.controls[arrayName].controls; let i = index">
        <ng-container [formGroupName]="i">
            <kendo-numerictextbox [formControlName]="'value'" [format]="'n0'" [decimals]="0" [spinners]="false" [min]="0"></kendo-numerictextbox>
        <span>{{item.hasError('required')}}</span>
        <span>{{item.valid}}</span>
        </ng-container>
    </tr>
</tbody>

What am I missing?

EDIT:

I create a Plunker with the answer:

https://plnkr.co/edit/l7gyONd4pLqqWGLGVjyb?p=preview

Upvotes: 2

Views: 3088

Answers (1)

Oleksii Miroshnyk
Oleksii Miroshnyk

Reputation: 470

In your implementation you push FormGroups to controls array. So if you iterate through controls array in your template you will iterate through form groups. Every form group will be invalid because some field inside are required, but every form group does not have required error because it is group and you did not add require check for all form group, but you did it for a control inside group.

Try to use this <span>{{item.get('value').hasError('required')}}</span>

Upvotes: 3

Related Questions