2

我知道我们可以FormGroup使用 FormArray 添加对象数组,如下所示:
https ://alligator.io/angular/reactive-forms-formarray-dynamic-fields/

ngOnInit() {
  this.orderForm = this.formBuilder.group({
    customerName: '',
    email: '',
    items: this.formBuilder.array([ this.createItem() ])
  });
}

createItem(): FormGroup {
  return this.formBuilder.group({
    name: '',
    description: '',
    price: ''
  });
}

addItem(): void {
  this.items = this.orderForm.get('items') as FormArray;
  this.items.push(this.createItem());
}

<div formArrayName="items"
  *ngFor="let item of orderForm.get('items').controls; let i = index;">
  <div [formGroupName]="i">
    <input formControlName="name" placeholder="Item name">
    <input formControlName="description" placeholder="Item description">
    <input formControlName="price" placeholder="Item price">
  </div>

  Chosen name: {{ orderForm.controls.items.controls[i].controls.name.value }}
</div>

但我想要数字数组而不是对象。
我们如何在 Angular 6.* 中做到这一点?
我们如何从中添加或删除数字项?

4

1 回答 1

4

您可以将任何表单控件而不是表单组传递给表单数组:

new FormGroup({
  // ...
  items: new FormArray([new FormControl(123)]),
});

Angular 附带的可能控件:FormGroup, FormArray, FormControl.

FormBuilder(我个人认为它已经过时,只是一种意见)只是为您创建这些对象。如果你想坚持下去试试

items: this.formBuilder.array([123])

添加和删​​除项目:

private addItem(value: number) {
    this.itemsFormArray.push(new FormControl(value));
}
private removeItem(value: number) {
    let index = this.itemsFormArray.controls.findIndex(control => { 
        return control.value == value;
    });
    this.itemsFormArray.removeAt(index);
}
private get itemsFormArray(): FormArray {
    return this.formGroup.get('items') as FormArray;
};
于 2018-07-03T08:36:48.003 回答