3

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

4

1 回答 1

2

我建议使用FormArray这个。使用FormArray,您的实现将如下所示:

对于组件类:

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);
  }

}

在模板中:

<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>

这是您参考的示例 StackBlitz

PS:我对您分享的 StackBlitz 进行了一些更新,包括 Angular 样式指南推荐的内容以及实际解决方案。希望有帮助。

于 2018-11-20T21:10:20.213 回答