这是我的JSON
[{
"id": 138,
"first_name": "John",
"last_name": "Doe",
"phone": [{
"label": "home",
"value": 546345
}, {
"label": "wife",
"value": 63456345
}]
}]
当我单击“编辑显示”输入字段时,我需要制作编辑表单。 我可以使用所有的东西,但是对于电话号码却遇到了问题,我无法获取contact_phone中所有对象的输入,只能输入第一个对象。
这是我的代码的一部分
<div formArrayName="phone">
<div *ngFor="let number of phoneFormGroup.controls; let i = index">
<div [formGroupName]="i" class="row">
<div class="col-xl-5 col-md-5 col-sm-12 col-12">
<input formControlName="value" type="number" placeholder="Number" />
</div>
<div class="col-xl-5 col-md-5 col-sm-12 col-10">
<input formControlName="label" type="text" placeholder="Label" />
</div>
<div class="col-xl-2 col-md-2 col-sm-12 col-2 newContactInputTitle">
<div class="removeNumber" (click)="removeNumber(i)"><i class="fa fa-times"></i></div>
</div>
</div>
</div>
<div class="addNumber d-flex h-100r" (click)="addNumber()"><i class="fa fa-plus-circle fa-2x" aria-hidden="true"></i>Add number</div>
</div>
答案 0 :(得分:1)
在这里<div *ngFor="let contact of contactFormGroup.controls; let i = index">
中,您正在设置contact
。
但是在您的输入中,您引用的是controls
:
<input formControlName="controls.number" type="number" placeholder="Number" />
<input formControlName="controls.value" type="text" placeholder="Label" />
尝试更改为formControlName="contact.number"
和formControlName="contact.value"
*看起来您应该引用contact.label
而不是contact.number
,因为这就是您的contact_phone
对象数组中的内容
答案 1 :(得分:1)
在for循环的createContactNumber
方法中,您仅返回列表中的第一个对象。
if (this.contact.contact_phone) {
for (let i = 0; i < this.contact.contact_phone.length; i++) {
return this.formBuilder.group({
label: [this.contact.contact_phone[i].label],
value: [this.contact.contact_phone[i].value]
});
}
} else {
return this.formBuilder.group({
label: [""],
value: [""]
});
}
我做了一些更改。首先,我将您的createContactNumber
重命名为getContactNumbersAsFormGroups
,它将返回FormGroups
的列表。
private getContactNumbersAsFormGroups(): FormGroup[] {
//check if user phone number exist, if yes show them in input, if not show empty input
let inputs: FormGroup[] = []
if (this.contact.contact_phone) {
for (let i = 0; i < this.contact.contact_phone.length; i++) {
inputs.push(this.formBuilder.group({
label: [this.contact.contact_phone[i].label],
value: [this.contact.contact_phone[i].value]
}));
}
} else {
inputs.push(this.getEmptyContactNumberForm());
}
return inputs;
}
方法getEmptyContactNumberForm
仅返回空格式。
private getEmptyContactNumberForm(): FormGroup {
return this.formBuilder.group({
label: [""],
value: [""]
});
}
下一个更改是在您的addContactNumber
方法中
this.contactList.push(this.getEmptyContactNumberForm());
最后是方法ngOnInit
ngOnInit() {
...
contact_phone: this.formBuilder.array(this.getContactNumbersAsFormGroups());
...
}