Formarray不会显示从service / api收到的所有记录

时间:2019-06-16 07:03:46

标签: angular7 angular-reactive-forms formarray webapi2

我正在尝试将从webapi接收的对象修补为有角反应形式。表单也有一个formarray。但是,尽管有3条或3条以上的记录,但只有2条记录被修补到反应形式的表单数组中。

我有两个实体noseries和noseriesList,其中noseries有零个或多个noseriesList。因此,从webapi获得noseries之后,我想将noseries的属性和导航列表“ noseriesLists”修补为反应形式。 其余属性均已正确打补丁,但导航列表“ noseriesLists”中只有2条记录被打补丁到嵌套在反应式表单内的formArray上。

//initialization of form
    this.noseriesForm = this.fb.group({
      id: [null],
      description: ['', Validators.required],
      code: [ '', Validators.compose([Validators.maxLength(10), Validators.required])],
      noSeriesList: this.fb.array([
         this.initLine(), this.initLine()
      ])
    });

//patching the object received from service to form
 this.route.params.subscribe(routeParam => {
      if (routeParam.id) {
        this.noseriesService.get(routeParam.id)
        .subscribe((data: NoSeries) => {
          this.isCreateMode = false;
          this.noseries = data;
          this.noseriesForm.patchValue(this.noseries);
          console.log(this.noseries, 'data from api');
          console.log(this.noseriesForm.value,'formvalue');
        });
      }

    });

//initialise formArray
  initLine(): FormGroup {
    return this.fb.group({
      id: [null],
      startingNoSeries: ['', Validators.required],
      endingNoSeries: '',
      lastUsedSeries: '',
      effectiveDate: [null],
      endingDate: [null],
      noSeriesId: [null]
    });
  }


记录从服务接收的数据显示3条noseriesList记录,而记录formvalue仅显示2条noseriesList记录。

1 个答案:

答案 0 :(得分:1)

首次初始化表单数组时,将添加两个空控件。这就是为什么当您将值修补到formgroup时,仅填充了这两个空控件。您应该在要修补值之前将要修补的控件数量填充到formarray中。

//patching the object received from service to form
this.route.params.subscribe(routeParam => {
    if (routeParam.id) {
        this.noseriesService.get(routeParam.id).subscribe((data: NoSeries) => {
          this.isCreateMode = false;
          this.noseries = data;

          const nsList = this.noseriesForm.get("noSeriesList") as FormArray;
          nsList.clear();
          this.noseries.forEach(_ => nsList.push(this.initLine()));

          this.noseriesForm.patchValue(this.noseries);
          console.log(this.noseries, 'data from api');
          console.log(this.noseriesForm.value,'formvalue');
        });
    }

});