Angular FormArray Push FormControl

时间:2019-12-10 20:28:37

标签: angular typescript

我需要添加公司的表单,我想在数据库中保存添加了公司的字符串列表,问题是在formarray中公司的值始终为空

<button (click)="addNewCompany()">Add new Company</button><br><br>
<form [formGroup]="myForm">
    <div formArrayName="companies">
        <div *ngFor="let comp of getForm(); let i=index>
            <fieldset>
                <legend>
                    <h3>COMPANY {{i+1}}: </h3>
                </legend>
                <label>Company Name: </label>
                <input formControlName="comp" /><span><button (click)="deleteCompany(i)">Delete Company</button></span>
            </fieldset>
        </div>
    </div><br>
  </form>


export class AppComponent {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      companies: this.fb.array([])
    });
  }

  getForm(): any {
    return this.myForm.get("companies")["controls"];
  }

  addNewCompany() {
    const control = <FormArray>this.myForm.get("companies");
    control.push(this.fb.control(''));
  }

  deleteCompany(index) {
    let control = <FormArray>this.myForm.controls.companies;
    control.removeAt(index);
  }

}

Stackblitz

1 个答案:

答案 0 :(得分:1)

您也非常方便地添加了StackBlitz演示!

<input [formControlName]="i" />

由于FormArray的项目将具有索引的0, 1, 2...,因此它们变为formControlName的值。您还需要使用[]表示法,否则它使用i作为字符串,而不是使用i的属性值,例如0、1