反应形式的数字数组,角度为6?

时间:2018-07-03 08:31:52

标签: angular angular6 angular-reactive-forms reactive-forms formarray

我知道我们可以使用FormArray向FormGroup添加对象数组,如下所示:
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. *中做到呢?
我们如何添加或删除数字项目?

1 个答案:

答案 0 :(得分:4)

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

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

可能附带以下角度的控件:FormGroupFormArrayFormControl

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