我有一个Angular应用程序,我从API获取数据并填充一个反应式表单。希望下面的代码是不言自明的。
复杂的是,一个报价中有QuoteItems,而这些QuoteLineItems又有QuoteLineItems。
this.quoteService.get(this.route.snapshot.paramMap.get('id'))
.subscribe(
result => {
this.quote = result;
this.quoteForm = this.fb.group({
quoteBy: new FormControl({ value: this.quote.quoteBy, disabled: true }),
design: new FormControl({ value: this.quote.design, disabled: true }),
quoteV2Items: this.fb.array([]),
});
for (const element of this.quote.quoteItems) {
this.quoteItems.push(this.fb.group({
quoteItemId: element.quoteItemId,
itemNumber: element.itemNumber,
location: element.location,
quoteLineItems: this.fb.array([]),
}));
for (const element2 of element.quoteLineItems) {
this.quoteLineItems(this.quote.quoteItems.indexOf(element)).push(this.fb.group({
quoteLineItemId: element2.quoteLineItemId,
description: element2.description,
rate: element2.rate,
quantity: element2.quantity,
total: element2.total,
}));
}
}
this.loading = false;
},
error => {
this.loading = false;
}
);
get quoteItems() {
return this.quoteForm.get('quoteItems') as FormArray;
}
quoteV2LineItems(index) {
return (this.quoteForm.get('quoteItems') as FormArray).at(index).get('quoteLineItems') as FormArray
}
问题是,当我转到页面时,每3次中就有1次,我认为表单在填充之前就已经显示出来了,并且页面没有正确呈现。我怀疑我可以通过确保在将加载设置为true之前完成for循环来解决这个问题——我该怎么做?
更新,实际上我确信这就是问题所在,若我有一个大对象,那个么每次刷新都会填充不同数量的嵌套对象。
更新:这是html:
<form [formGroup]="quoteForm" autocomplete="off">
<input matInput formControlName="quoteBy">
<input matInput formControlName="design">
<div formArrayName="quoteItems" *ngIf="quoteItems && quoteItems.length > 0">
<div *ngFor="let controls of quoteItems.controls;let i=index" [formGroupName]="i">
{{controls.get('itemNumber').value}}
{{controls.get('location').value}}
<ng-container>
<div formArrayName="quoteLineItems"
*ngFor="let controls of quoteLineItems(i).controls;let j=index" [formGroupName]="j">
{{controls.get('description').value}}
{{controls.get('rate').value | currency}}
{{controls.get('quantity').value}}
{{controls.get('total').value | currency}}
</div>
</ng-container>
</div>
</div>
</form>
理想情况下,一旦知道是否填写了this.quote
,就应该控制是否要显示表单。我建议添加以检查报价表和您是否已完成加载
*ngIf="quoteForm && !loading"
这应该添加到<form [formGroup]="quoteForm" autocomplete="off">