在removeAt()的输入中,Angular 4表单数组的值不正确

时间:2017-06-13 03:45:21

标签: forms angular angular-reactive-forms

我创建了一个Plunker来演示问题

https://embed.plnkr.co/pgu7szf9ySwZSitOA5dq/

如果删除#2,则会看到#5在最后两个框中显示两次。我无法弄清楚为什么会这样。

1 个答案:

答案 0 :(得分:3)

您应该将FormArray嵌套在FormGroup中,如下所示:

export class AppComponent implements OnInit {
    public formG: FormGroup;
    public formArray: FormArray;

    constructor(private fb: FormBuilder) { }

    ngOnInit() {
      this.createForm(); 
    }


    createForm() {
      this.formArray = this.fb.array([
        this.fb.control(1),
        this.fb.control(2),
        this.fb.control(3),
        this.fb.control(4),
        this.fb.control(5),
      ]);
      this.formG = this.fb.group({
        farray: this.formArray
      });
      console.log(this.formArray);
    }

    addQuestion() {
      this.formArray.push(this.fb.control(''));
    }

    removeQuestion(i) {
      this.formArray.removeAt(i);
    }
}

模板:

<div class="container" [formGroup]="formG">
  <div formArrayName="farray">
    <div class="row form-inline" *ngFor="let question of formArray.controls; let i = index">
      <textarea class="form-control" [formControlName]="i"></textarea>
      <button (click)="removeQuestion(i)" class="btn btn-secondary">Remove</button>
    </div>
  </div>
</div>
<button (click)="addQuestion()" class="btn btn-secondary">Add</button>

表格在行动:official documentation