我无法理解索引值在 ngFor 循环中的作用以及它如何帮助创建动态表单字段



我正在尝试学习如何以角度创建动态表单字段,我无法理解 ngFor 循环中索引值的工作逻辑,以及该索引值如何帮助创建动态表单字段

产品表单组件

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl } from '@angular/forms';
@Component({
  selector: 'app-product-form',
  templateUrl: './product-form.component.html',
  styleUrls: ['./product-form.component.css']
})
export class ProductFormComponent implements OnInit {
  constructor(private fb: FormBuilder) { }
  productForm: FormGroup;
  ngOnInit() {
    /* Initiate the form structure */
    this.productForm = this.fb.group({
      title: [],
      selling_points: this.fb.array([this.fb.group({point:''})])
    })
  }
  get sellingPoints() {
    return this.productForm.get('selling_points') as FormArray;
  }
  /////// This is new /////////////////
  addSellingPoint() {
    this.sellingPoints.push(this.fb.group({point:''}));
  }
  deleteSellingPoint(index) {
    this.sellingPoints.removeAt(index);
  }
  //////////// End ////////////////////
}

产品表单组件.html

<h1>Edit Product</h1>
<form [formGroup]="productForm">
  <label>
    Title: <input formControlName="title" />
  </label>
  <h2>Selling Points</h2>
  <div formArrayName="selling_points">
    <div *ngFor="let item of sellingPoints.controls; let pointIndex=index" [formGroupName]="pointIndex">
        {{pointIndex}} {{item}}
        <label>
      Selling Point: <input formControlName="point" />
    </label>
    <button type="button" (click)="deleteSellingPoint(pointIndex)">Delete Selling Point</button>
    </div>
    <button type="button" (click)="addSellingPoint()">Add Selling Point</button>
  </div>
</form>
{{ this.productForm.value | json }}

表单组正在使用数组。此处声明:

https://angular.io/api/forms/FormArray

selling_points: this.fb.array([this.fb.group({point:''})])

表单数组通过偏移数值访问。

https://angular.io/api/forms/FormArray#at

表单组

指令使用数组偏移量将表单组分配给 DOM 元素。

https://angular.io/api/forms/FormGroupName

<div *ngFor="let item of sellingPoints.controls; let pointIndex=index" [formGroupName]="pointIndex">

分配给 DOM 元素后。可以相对于该组使用控件。

<input formControlName="point" />

上面引用了当前表单组中的表单控件。

您的代码还通过使用循环索引值删除数组项来删除窗体组。

deleteSellingPoint(index) {
    this.sellingPoints.removeAt(index);
  }

因此,如果您调用this.sellingPoints.removeAt(0)它将删除第一组。