订阅观察值变化时,为什么我动态创建的表单控件丢失了

时间:2019-05-06 16:24:21

标签: angular typescript observable angular-reactive-forms

我已经动态创建了一个包含五个控件的表单数组。我正在订阅表单数组上的更改。值更改返回中缺少窗体控件之一。

我已经遍历了代码,以确保缺少的控件与出现的控件具有相同的设置。

动态创建代码... 首先,我要进行API调用...

this.userProfile.userEmployeeId.subscribe(
      dataEmployeeId => {
        this.employeeId = dataEmployeeId;
        /**
         * Observable to pull the employee timecards
         */
        this.employeeService.getEmployeeTimeCards(this.employeeId).subscribe(
          (datagetEmployeeTimeCards: ITimecard[]) => {
            datagetEmployeeTimeCards.forEach((elTimecard, index) => {
              // Populate form fields with timecard information
              if (elTimecard.timecardDets.length > 0) {
                elTimecard.timecardDets.forEach((elTimecardDets, i) => {
                  this.addWorkTracked(elTimecardDets);
                });
              }
            });
          },
          (err: any) => console.log(err)
        );
      },
      (err: any) => console.log(err)
    );

调用该方法以根据API返回创建动态控件

addWorkTracked(data?: ITimecardDet): void {
    this.timecardDets.push(this.buildWorkTracked(data));
  }
buildWorkTracked(data?: ITimecardDet): FormGroup {
return new FormGroup({
    payCategory: new FormControl(this.buildPayCategories()),
    shiftDifferential: new FormControl(
    this.buildShiftDifferentialCategories()
    ),
    overtimeCategory: new FormControl(this.buildOvertimeCategories()),
    hoursWorked: new FormControl('0:00'),
    earnings: new FormControl({ value: null, disabled: true }) // This is the missing control
});
}

创建可观察的代码...

const timecardDetsChanges = this.timecardForm.controls['timecardDets'].valueChanges;
timecardDetsChanges.subscribe(
    value =>
        value.forEach(element => {
            // All form controls appear except for the earnings control
        })
    );

这是html ...

<input
    matInput
    formControlName="earnings"
    id="{{ earnings + i }}"
    type="number"
    data-number-to-fixed="2"
    readonly="true"
/>

我想弄清楚为什么缺少的控件没有显示,所以我可以对该字段采取措施。

0 个答案:

没有答案