我有以下JSON,我希望将其映射到表单:
{
"lineItemId": 0,
"count": 0,
"fixtures": [
{
"fixtureId": 0,
"fixtureName": "string",
"total": 0,
"completed": 0,
"guestDetails": [
{
"id": 0,
"forename": "string",
"surname": "string",
"email": "string",
"telephone": "string",
"specialInstructions": "string",
"completed": true,
"dietaryRequirements": [
{
"id": 0,
"name": "string",
"isRequired": true
}
]
}
]
}
]
}
然后我将以下工作打字稿映射到formbuilder:
this.myForm = this.fBuilder.group({
guestDetailsForm: this.fBuilder.array([])
});
this.httpService.getGuestDetails(this.eventId, this.passedIdValue)
.subscribe(data => {
this.fixturesArray = data.fixtures;
console.log(this.fixturesArray);
this.fixturesArray.forEach(fixturesArrayElement => {
this.guestDetailsArray = fixturesArrayElement.guestDetails;
this.guestDetailsArray.forEach(element => {
(<FormArray>this.myForm.get('guestDetailsForm')).push(this.fBuilder.group({
id: [element.id],
forename: [element.forename],
surname: [element.surname, Validators.required],
email: [element.email],
telephone: [element.telephone],
dietaryRequirements: [element.dietaryRequirements]
}));
});
});
},
error => alert(error),
() => console.log(""));
我可以列出姓,姓,电子邮件等,但不会在以下模板中显示“dietRequirements”数据的文本字段。我认为这与我的内部* ngFor循环有关,但似乎没有任何效果。有帮助吗? :)
<div class="generalForm" formArrayName="guestDetailsForm">
<div *ngFor="let guest of myForm.controls.guestDetailsForm.controls; let i=index" [ngClass]="{'guestForm show' : viewingGuestId == i, 'guestForm hide' : viewingGuestId != i}">
<div [formGroupName]="i">
<input type="hidden" formControlName="id" />
<ol>
<li class="inputQuestion">
<label>Forename</label>
<input type="text" formControlName="forename" />
</li>
<li class="inputQuestion">
<label>Surname</label>
<input type="text" formControlName="surname" />
<div [hidden]="myForm.controls.guestDetailsForm.controls[i].controls.surname.valid" class="inlineError">Required
</div>
</li>
<li class="inputQuestion">
<label>Email</label>
<input type="text" formControlName="email" />
</li>
<li class="inputQuestion">
<label>Telephone</label>
<input type="text" formControlName="telephone" />
</li>
<li class="dietaryRequirementsQuestion" formArrayName="dietaryRequirements">
<div *ngFor="let meals of myForm.controls.guestDetailsForm.controls[i].controls.dietaryRequirements; let x=index">
<div [formGroupName]="x">
<input type="text" formControlName="name" />
</div>
</div>
</li>
</ol>
</div>
</div>
</div>
答案 0 :(得分:5)
我会创建FormArray
而不是dietaryRequirements
buildFormArrayOfGroupsFromArr(arr) {
return this.fBuilder.array(arr.map(x => this.fBuilder.group(x)));
}
...
dietaryRequirements: this.buildFormArrayOfGroupsFromArr(element.dietaryRequirements)
之后你写下面的html:
<div *ngFor="let meals of myForm.controls.guestDetailsForm.controls[i].controls.dietaryRequirements.controls; let x=index">
<div [formArrayName]="x">
<input type="text" formControlName="name" />
</div>
</div>
您还可以查看 Plunker Example