在Angular 7中动态添加行以形成表单

时间:2019-12-10 09:20:48

标签: angular

我正在尝试向表单添加行。每行有3个输入字段。

这是我到目前为止所做的。

export class MedicationGrid {
   title1:string;
   title2:string;
   title3:string;
}

组件html

  <li class="am-row" *ngFor="let dynamic of dynamicArray; let i = index;">
    <div class="medication-name">
    <input  type="text" class="form-control am-medicine" placeholder="Medicine" [(ngModel)]="dynamicArray[i].title1"  name="medicine" required />
    </div>
   <div class="medication-dosage">
   <input type="text" class="form-control am-dosage" placeholder="Dosage"       [(ngModel)]="dynamicArray[i].title2" name="dosage" />
   </div>
   <div class="medication-frequency">
   <input type="text" class="form-control am-frequency" placeholder="Frequency" [(ngModel)]="dynamicArray[i].title3" name="frequency" />
  </div>
  <div class="medication-add">
   <img src="../../../assets/img/actionModal/add.png" (click)="addMedicationRow(i)"  />
  </div>
 </li>

component.ts

ngOnInit() {
    this.newDynamic = {title1:"", title2:"", title3:""};
    this.dynamicArray.push(this.newDynamic);
}

addMedicationRow(index) {
   this.newDynamic = {title1:"", title2:"", title3:""};
   this.dynamicArray.push(this.newDynamic);
   return true;
 }

我可以以此添加新行。但是问题是,当我在字段中输入一些数据并单击添加按钮时,所有数据都消失了,并插入了新行。我该如何解决?

2 个答案:

答案 0 :(得分:0)

本指南的完全摘录自:https://alligator.io/angular/reactive-forms-formarray-dynamic-fields/

”“因此,您有一个表单,并且希望根据对用户事件的响应来动态添加表单字段?使用Reactive Forms和FormArray很容易。FormArray有点像FormGroup,并且其用法非常相似,区别在于它用作包裹任意数量的FormControl,FormGroup甚至其他FormArray实例的数组。”

导入FormArray

首先,除了其他表单导入之外,您还想从Angular表单模块中导入FormArray:

import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

// ...

初始化表格

现在,我们将使用ngOnInit挂钩中的FormBuilder初始化表单。在此示例中,我们将创建一个订单表单,允许用户动态添加新商品:

orderForm: FormGroup;
items: FormArray;

constructor(private formBuilder: FormBuilder) {}

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

我们的items实例是一个窗体数组,而不是窗体控件,并且我们正在调用createItem方法来创建一个窗体组作为数组中的第一项。这是我们的createItem方法的样子:

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

动态添加到FormArray

现在有趣的是,我们可以像对待常规数组一样对待FormArray并将新项目推入其中:

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

现在,这就像用户单击添加新项目时在模板中调用addItem方法一样简单。

模板中的FormArray

最后,我们在模板中使用formArrayName指令绑定到表单数组:

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

请注意,我们的formGroupName指令现在如何获取索引而不是名称,并使用ngFor给我们的索引进行设置。

您还可以看到一种遍历我们的表单的方法,可以在模板中获取表单控件的值。

答案 1 :(得分:0)

您可以使用FormGroupFormControl创建控件。让我举个例子:

可以看到at stackblitz example

HTML:

<form [formGroup]="myForm">
    <ng-container *ngFor="let group of myForm.controls |keyvalue">
        <div style="margin:20px;" [formGroup]="group.value">
            <label for="">{{group.key}} test</label>
            <input type="text" formControlName="name">
            <button type="button" (click)="onAddMedicine(group.value)">Add Medicine</button>
            <div formArrayName="medicineList">
                <div *ngFor="let item of medicineArray(group.value).controls; let i = index">
                    <label for="">Medicine row</label>
                    <input [formControlName]="i">
          <button (click)="removeMedicine(group.value,i)">remove</button>
      </div>
                </div>
            </div>
    </ng-container>
</form>
<pre>
{{myForm?.value|json}}
</pre>

TypeScript:

public myForm: FormGroup;

ngOnInit() {
    this.myForm = new FormGroup({});
    for(let item of ['item1']) {
        this.myForm.addControl(item,
            new FormGroup({
                name: new FormControl(),
                medicineList: new FormArray([])
            })
        )
    } 
} 

onAddMedicine(group:FormGroup) {
    (group.get('medicineList') as FormArray).push(new FormControl())
}

medicineArray(group:FormGroup):FormArray
{
    return group.get('medicineList') as FormArray
}

removeMedicine(group:FormGroup,index:number)
{
    (group.get('medicineList') as FormArray).removeAt(index)
}