4

In my Angular 7 app using reactive forms I'm creating input elements based on an *ngFor loop, so I end up with an input dynamically named:

<nav class="level" *ngFor="let work of workLeft">
    <input [formControlName]="work.abbrev">

which of course works fine, but now I'm trying to add the validation error messages to the form, but I'm not sure how to "address" the item. For example, the div would normally look like so:

<div *ngIf="name.errors.required">

but I don't have name there as it's the dynamic work.abbrev value. What's the right way to handle this?

You can see my attempt here: https://stackblitz.com/edit/angular-8zevc1

Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83
Gargoyle
  • 9,590
  • 16
  • 80
  • 145
  • Is `workLeft` some sort of a `FormArray`? If not, I recommend it to be one. That way you can create a `get`ter on your Component Class and use the `at` API on a `FormArray` to get the relevant `FormControl`/`FormGroup` – SiddAjmera Nov 20 '18 at 19:53
  • No, it's just an array of objects that was returned from an http webservice. But it's not a class variable, it's just created in the call that generates the form data. – Gargoyle Nov 20 '18 at 19:54
  • I'm not sure how your comment helps though as I'm asking about how to deal with it in the HTML itself, and I specifically mentioned not wanting to use a FormArray. – Gargoyle Nov 20 '18 at 19:58
  • 1
    That's because `FormArray` is something that is generally used in such scenarios. You want to show validation errors for each item in `workLeft` and it again is a form control. Also, I don't think you will need to keep any mapping to track the index and the form control anywhere. That's not how it works. – SiddAjmera Nov 20 '18 at 20:02
  • OK, if it's the right way so be it. Can you show me what the div's *ngIf should look like please? – Gargoyle Nov 20 '18 at 20:03
  • Would it be possible for you to create a Sample StackBlitz replicating this issue? Or at least add some sample json data to work with? – SiddAjmera Nov 20 '18 at 20:04
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/183981/discussion-between-gargoyle-and-siddajmera). – Gargoyle Nov 20 '18 at 20:34

1 Answers1

3

I suggest using FormArray for this. With FormArray, here's how your implementation is going to look like:

For the Component Class:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';

export interface Data {
  abbrev: string;
  max: number;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  workForm: FormGroup;
  workLeft: any[];

  constructor(private fb: FormBuilder) {}

  ngOnInit () {

    this.workForm = this.fb.group({
      points: this.fb.array([])
    });

    this.fillFormArray();
  }

  private fakeWebserviceCall(): Data[] {
    return [
      { abbrev: 'foo', max: 12 },
      { abbrev: 'bar', max: 10 }
    ];
  }

  private fillFormArray() {
    this.workLeft = this.fakeWebserviceCall();
    const formControlsArray = this.workLeft.map(work => this.fb.control(work.abbrev, [Validators.min(0), Validators.max(work.max)]));
    formControlsArray.forEach(control => this.points.push(control));
    console.log(this.workForm.value);
  }

  get points(): FormArray {
    return <FormArray>this.workForm.get('points');
  }

  pointAt(index) {
    return (<FormArray>this.workForm.get('points')).at(index);
  }

}

And in the template:

<form [formGroup]="workForm">
    <div formArrayName="points">
        <div *ngFor="let point of points.controls; let i = index">
      {{ workLeft[i].abbrev }}: <input type="number" [formControlName]="i">
      <div *ngIf="pointAt(i).invalid && (pointAt(i).dirty || pointAt(i).touched)">
        The field is invalid
      </div>
    </div>
  </div>
</form>

Here's a Sample StackBlitz for your ref.

PS: I've made a few updates to the StackBlitz that you've shared including things that Angular Style Guide recommends along with the actual solution. Hope that helps.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110