在表单数组中添加和删除输入字段(活动表单)

时间:2019-08-07 12:38:40

标签: angular angular7 reactive-forms

我有一个本地变量,其中后端数据以数组形式接收:

itemsFromBackend: ["Item1", "Item2"]

创建新阵列

items: FormArray

在表单组中:

ngOnInit() {
  this.form = this.formBuilder.group({
    items: this.formBuilder.array([ this.createItem() ])
  });
}

创建项目

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

添加项目:

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

在HTML

<div formArrayName="items" *ngFor="let item of form.get('items').controls; let i = index ">
      <div *ngFor="let item of itemsFromBackEnd" [formGroupName]="i">
        <input value={{item}} />
        <section>
            <button
              mat-raised-button
              color="primary"
              type="button"
              (click)="addItem()"
            >
              <i class="material-icons"> add </i>
            </button>
          </section>
      </div>
    </div>

我现在收到两个带有后端值的字段,但是当我单击添加按钮时,它应该显示一个新的输入字段,但是它将添加另外两个带有后端值的输入字段。单击添加按钮时,我需要一些帮助来显示新的输入字段。谢谢。

1 个答案:

答案 0 :(得分:1)

通过这些更改,它可以按照您的要求运行

html:

<div [formGroup]="form">
  <div formArrayName="items" *ngFor="let item of getItems(); let i = index">
    <input value="{{ itemValue(item) }}" />
  </div>
  <section>
    <button mat-raised-button color="primary" type="button" (click)="addItem()">
     <i class="material-icons"> add </i>
    </button>
  </section>
</div>

ts:

itemsFromBackEnd = ['Item1', 'Item2'];
form: FormGroup;

constructor(private formBuilder: FormBuilder) {}

ngOnInit() {
  this.form = this.formBuilder.group({
    items: this.formBuilder.array([])
  });

  this.itemsFromBackEnd.forEach(i => this.addItem(i));
 }

 getItems() {
   return (<FormArray>this.form.get('items')).controls;
 }

 itemValue(item: any) {
   return item.controls.value.value;
 }

 createItem(name?: string): FormGroup {
   return this.formBuilder.group({
     value: name ? name : ''
   });
}

addItem(name?: string): void {
   const items = this.form.get('items') as FormArray;
   items.push(this.createItem(name));
}