我正在使用动态表单来按角度创建表单。我用一些可用的食材来代表我的食材,但是由于您可以添加多个食材,因此我需要动态生成选择。
我的html:
<form [formGroup]="mealForm">
<input formControlName="mealName" type="text" class="form-control" /><br/>
<select formControlName="ingredients" class="form-control">
<option selected value="">Select an ingredient</option>
<option *ngFor="let ingredient of myfoods" value="{{ ingredient.id }}">{{ ingredient.name }}</option>
</select><br/>
<div formArrayName="additionalIngredients" *ngFor ="let ingredient of additionalIngredients.controls; let i=index">
<select formControlName="i" class="form-control">
<option selected value="">Select an ingredient</option>
<option *ngFor="let ingredient of myfoods" value="{{ ingredient.id }}">{{ ingredient.name }}</option>
</select>
</div>
<button (click)="addAdditionalIngredients()" type="button">Add ingredient</button>
</form>
我的TS代码:
mealForm: FormGroup;
get additionalIngredients(){
return this.mealForm.get('additionalIngredients') as FormArray;
}
addAdditionalIngredients(){
this.additionalIngredients.push(this.fb.control(''));
}
constructor(private fb: FormBuilder){}
ngOnInit() {
this.mealForm = this.fb.group({
mealName: [''],
ingredients: [''],
additionalIngredients: this.fb.array([])
});
}
我面临的问题是,当我添加动态选择时,选项为空,但是当我取消选择后,选择将被填充,但不会传递该值。这是我通过选择任何一种选项得到的示例json:
{ "mealName": "new meal", "ingredients": "1", "additionalIngredients": [ "", "" ] }
如您所见,动态选择的“ additionlINgredients”为空,但在这种情况下,我的静态一个“成分”的值为1-预期值为成分的数字值或id ...
答案 0 :(得分:1)
您应将formControlName="i"
替换为[formControlName]="i"
,因为在第一种情况下,您将字符串值'i'分配给formControlName而不是i的值:
<div formArrayName="additionalIngredients" *ngFor ="let ingredient of additionalIngredients.controls; let i=index">
<select [formControlName]="i" class="form-control">
<option selected value="">Select an ingredient</option>
<option *ngFor="let ingredient of myfoods" value="{{ ingredient.id }}">{{ ingredient.name }}</option>
</select>
</div>