将多个值推送到FormArray

时间:2019-05-25 07:51:30

标签: angular6 angular7 formarray formgroups

我实际上被困在这里。尝试搜索网络,但没有发现足够有用的东西。

我正在尝试将值推送到FormArray。问题是我是数组值,需要将其插入到窗体中。我只能添加一条记录。它将最后一个迭代的数组对象插入到formArray中。

下面是代码:

.TS

salesResult: FormArray;

async ClickSearch() {
//this method get the dto with the mapped formValues. 
const getSalesResult = this.salesEvidenceFormService.getSalesSearchFormGroup(
  this.form
);
//the above method form values passed to the web-api to return result. I get 200 records here. 
const salesSearchResults: any = await this.salesEvidenceService.getSalesSearchData(
  getSalesResult
);

//getting the formArray. this I have used as an arry form. As shown in below code
this.salesResult = this.form.get('salesSearchResult') ;

for (let item of salesSearchResults) {
  this.salesResult.controls[0].setValue(item);
  //this.form.controls.salesSearchResult.value.address = item.address;
}
}

public async form(valuationId: any): Promise<FormGroup> {
const form: FormGroup = this.formBuilder.group({
  id: valuationId,      
  siteAreaUnit: 'm2',
  lettableAreaUnit: 'm2',
  selectedDateRange: 0,
  selectedQuickChoice: '',
  metroNonMetro: 'ALL',
  salesSearchResult: this.formBuilder.array([
    this.getSalesSearchResultForm()
  ])
});
return await form;
  }

getSalesSearchResultForm(): FormGroup {
return this.formBuilder.group({
  id: this.formBuilder.control(''),
  masterId: this.formBuilder.control(''),
  address: this.formBuilder.control(''),
  salePrice: this.formBuilder.control(''),
  saleDate: this.formBuilder.control(''),
  initialYield: this.formBuilder.control(''),
  equivalentYield: this.formBuilder.control(''),
  nlaPsm: this.formBuilder.control(''),
  siteAreaPsm: this.formBuilder.control(''),
  lettableArea: this.formBuilder.control(''),
  wale: this.formBuilder.control(''),
  description: this.formBuilder.control(''),
  commercialSalesExists: this.formBuilder.control(''),
  documentId: this.formBuilder.control(''),
  totalRecord: this.formBuilder.control('')
});

}

我只想将记录插入到我的表单中。这样我就可以在html中插入它,以显示从API返回的记录。我不知道我在做什么错

2 个答案:

答案 0 :(得分:1)

我也有类似的问题,并发布了问题。我帖子中“ ysf”的答案帮助我解决了这个问题。您可以通过“ ysf”在注释中找到解决方案。尽管该帖子很旧,但我希望它能对您有所帮助。该帖子的链接为:-

Formarray doesnt show all the records received from service/api

答案 1 :(得分:0)

当我使用Push方法时,我做对了。下面是我实现的。一个一般的例子:

const tempContainer = this.formBuilder.array([]);
for (const current of formArray.controls) {
  const existing = this.saveForm.controls.find(
    x => x.value.Id === current.value.Id
  );

  if (existing) {
    tempContainer.push(existing);
  } else {
    tempContainer.push(current);
  }
}