Angular 动态表单控件

Angular Dynamic Form Controls

我用 FormArray 创建了动态表单。我不想删除第一个实例的按钮(因为我不想删除第一个实例)。 HTML代码

<div>
      <label>Name</label>
      <button type="button" class="btn btn-sm btn-primary float-right" (click)="addName()">Add Caption</button>
      <div formArrayName="firstName" *ngFor="let n of name().controls, let i=index">
        <div [formGroupName]="i" class="form-inline">
          <input formControlName="name" type="text" class="form-control mb-2 mr-sm-2">
          <select formControlName="option" class="form-control mb-2 mr-sm-2">
            <option value=null selected disabled>Select a option</option>
            <option value="1">1st</option>
          </select>
          <button type="button" class="btn btn-sm btn-danger mb-2" (click)="removeName(i)">Remove</button>
        </div>
      </div>
    </div>

TypeScript 代码

Form: FormGroup = this.fb.group({
firstName: this.fb.array([
  this.newName()
])
})

name(): FormArray {
return this.Form.get("firstName") as FormArray
}

newName(): FormGroup {
return this.fb.group({
  name: [],
  option: []
  })
}

addName() {
this.name().push(this.newName());
}

removeName(i: number) {
  this.name().removeAt(i);
 }

我想禁用和隐藏 FormArray 的第一个元素的删除按钮。

您已经有一个保存索引的变量。使用 *ngIf 检查索引变量与零的相等性,如下所示:

<button *ngIf="i !== 0" type="button" class="btn btn-sm btn-danger mb-2" (click)="removeName(i)">Remove</button>