如何在Angular 6中为一个组件的FormArray附加另一个组件的值

时间:2018-09-16 12:44:22

标签: angular angular-ui-router angular-reactive-forms

我想在两个组件之间使用相同的FormArray来保存数据。这两个组件代码都看起来像这样:

xyz.component.ts

createForm(data: any): FormGroup {
  return this.formBuilder.group({
    contractId: [data ? data.contractId : ''],
    contractName: [data ? data.contractName : '', Validators.required],
    contractServiceList: this.formBuilder.array(
      this.createContractService(data ? data.contractServiceList : null), this.arrayValidator()
    )
  });
}

createContractService(data: any[] | null): FormGroup[] {
  return data ?
    data.map(x => {
      let group = this.formBuilder.group({
        serviceId: [x.serviceId, Validators.required],
        copay: [x.copay, Validators.required],
        coinsurance: [x.coinsurance, Validators.required],
        deductibleApplies: [x.deductibleApplies, Validators.required],
        penaltyApplies: [x.penaltyApplies, Validators.required],
      });
      return group;
    }) : [this.formBuilder.group({
      serviceId: ['', Validators.required],
      copay: ['', Validators.required],
      coinsurance: ['', Validators.required],
      deductibleApplies: ['', Validators.required],
      penaltyApplies: ['', Validators.required],
    })];
}

abc.component.ts

createForm(data: any): FormGroup {
  return this.formBuilder.group({
    contractId: [data ? data.contractId : ''],
    contractName: [data ? data.contractName : ''],
    contractServiceList: this.formBuilder.array(
      this.createContractService(data ? data.contractServiceList : null), this.arrayValidator()
    )
  });
}

createContractService(data: any[] | null): FormGroup[] {
  return data ?
    data.map(x => {
      let group = this.formBuilder.group({
        penaltyRule: [x.penaltyRule, Validators.required],
        penaltyType: [x.penaltyType, Validators.required],
        penaltyValue: [x.penaltyValue, Validators.required],
        deductibleAppliesPenalty: [x.deductibleAppliesPenalty, Validators.required]
      });
      return group;
    }) : [this.formBuilder.group({
      penaltyRule: ['', Validators.required],
      penaltyType: ['', Validators.required],
      penaltyValue: ['', Validators.required],
      deductibleAppliesPenalty: ['', Validators.required]
    })];
}

点击“保存”按钮后,它将导航到下一个组件,因此在从第一个保存值之后,FormArray也应在第二个之后附加值。

0 个答案:

没有答案