angular5如何提交嵌套的反应形式

问题描述 投票:0回答:1

我可以通过以下代码创建嵌套表单(没有提交函数):https://plnkr.co/edit/vSODkb8i7o54X3fST9VF?p=preview

现在,我想提交表单,但有两种类型的错误:

  1. AppComponent.html:32 ERROR TypeError:无法读取未定义的属性“电子邮件”
  2. 保存时,会创建一个新行,但不会创建相应的输入。

我创建了stackbliz:https://stackblitz.com/edit/angular-tqrest

app.component.ts

constructor(private fb: FormBuilder, 
  private contractService: ContractService) { 
}

ngOnInit() {
  this.contractService.getContracts().subscribe(contracts => {
    this.contracts = contracts;
});

  this.trustForm = this.fb.group({
    contracts: this.fb.array([])
  });

  this.addContract();
}

initContract() {
  return this.fb.group({
    name: '',
    emails: this.fb.array([])
  });
}

addContract() {
  const contractArray = <FormArray>this.trustForm.controls['contracts'];
  const newContract = this.initContract();

  contractArray.push(newContract);
}

removeContract(idx: number) {
  const contractsArray = <FormArray>this.trustForm.controls['contracts'];
  contractsArray.removeAt(idx);
}

onSubmit(contract: Contract) {
  this.contractService.addContract(contract);
}

我怎么解决这个问题?

angular form-submit nested-forms
1个回答
1
投票

Part 1

你必须将表格中的Contract传递给你的onSubmit()函数。

<form [formGroup]="trustForm" (ngSubmit)="onSubmit(trustForm.value.contracts)">

此外,您会注意到我将type属性type="button"添加到您的“添加其他电子邮件+”和“添加其他联系人+”按钮。这可以防止单击这些按钮时触发onSubmit()事件。

如果你删除我添加到你的按钮的type属性,你会发现每次你点击任何一个时它们都会激活onSubmit()事件。这是默认的html按钮行为。默认情况下,所有按钮都是type="submit",除非另有明确声明。 MDN Docs: The Button Element

Part 2

您将需要更新您的contract.service.ts以使用Rxjs主题。您的原始方法不起作用,因为您只发送了一次Observable。使用Subject,您可以在Contracts阵列增长或更新时继续发送更新。

请参阅附加的更新的StackBlitz以获取工作代码:

StackBlitz Demo

© www.soinside.com 2019 - 2024. All rights reserved.