反应形式的数字数组,Angular 6?

Array of numbers in Reactive Forms, Angular 6?

我知道我们可以使用 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.*?
怎么办 我们如何从中添加或删除数字项?

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

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

angular 附带的可能控件: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;
};