基于Angular 7+中键值对的递归形式创建输入字段



我正在尝试创建一个formArray,它将包含要在模板中显示为标签和输入字段的键值对。

在阅读了几篇文章(以及我的错误控制台(之后,这就是我到目前为止所得到的,但没有结果:

组件.ts

foodFormArray = new FormArray([]);
...
this.foodFormArray.push(new FormGroup({"foodName" : new FormControl("Pizza"), "foodOrigin": new FormControl("Italy")}));  
this.foodFormArray.push(new FormGroup({"foodName" : new FormControl("Pho"), "foodOrigin": new FormControl("Vietnam")}));  
this.foodFormArray.push(new FormGroup({"foodName" : new FormControl("Raclette"), "foodOrigin": new FormControl("France")})

模板

<div *ngFor="let control of foodFormArray.controls; index as i">
<div [formGroup]="control">
<input [formControlName]="foodName" />
</div>
</div>

任何帮助都将不胜感激,谢谢!

如果你想用一个真正的ng-template来处理它,这就是处理方法。

使用*ngTemplateOutlet创建一个调用模板的循环,并传递cojntroller&它的索引。app.component.html

<ng-container *ngFor="let foodForm of foodForms">
<ng-content
*ngTemplateOutlet="
nameOfYourTemplate;
context: {
attributes: foodForm,
controlIndex: i
}
"
></ng-content>
</ng-container>
<!-- The template : can be used for recursive, just call the template into it's own -->
<ng-template #nameOfYourTemplate let-i="attributes" let-controlIndex="controlIndex">
<div [formGroup]="itemForm">
<ng-container formArrayName="foodFormArray">
<ng-container [formGroupName]="controlIndex">
<mat-form-field>
<mat-label>{{ i.title }}</mat-label>
<input [name]="i.id" [formControlName]="i.id" matInput />
</mat-form-field>
<!-- here, add <ng-content *ngTemplateOutlet="nameOfYourTemplate;" if you want a real recursive function -->
</ng-container>
</ng-container>
</div>
</ng-template>

那么,我建议创建一个fromGroup,我想,这是你的误解。因为您确实尝试将control用于[formGroup],但control应该是formArrayName的用户app.component.ts

itemForm = new FormGroup({})

constructor(protected _formBuilder: FormBuilder) {
this.itemForm = this._formBuilder.group({
foodForms = new FormArray([]),
})
}

我没有测试代码,但它应该可以工作,或者至少为您指明了正确的方向。

非常感谢,@Raphael:(

这就是最终对我有效的

在组件中。ts
worldFoodForms: FormArray = this.fb.array([ this.fb.group({"foodName" : this.fb.control("Pizza"), "foodOrigin": this.fb.control("Italy")}), this.fb.group({"foodName" : this.fb.control("Pho"), "foodOrigin": this.fb.control("Vietnam")}) ]);

以及在template.html中
<div *ngFor="let control of singleValueFieldsForm.controls; index as i "> <strong>{{control.controls.key.value}}</strong> <input [formControl]="control.controls.value"></div>

最新更新