我需要添加公司的表单,我想在数据库中保存添加了公司的字符串列表,问题是在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);
}
}
答案 0 :(得分:1)
您也非常方便地添加了StackBlitz演示!
<input [formControlName]="i" />
由于FormArray
的项目将具有索引的0, 1, 2...
,因此它们变为formControlName
的值。您还需要使用[]
表示法,否则它使用i
作为字符串,而不是使用i
的属性值,例如0、1