首页 > 解决方案 > 角度反应形式:将子组件值传递给父组件

问题描述

我以角度实现反应形式。我无法将价值从孩子传递给父母。

父表单示例:

<div class="fields-wrap" [formGroup]="parent">
<div class="input-wrap">
  <child-component></child-component>
</div>
<input type"button">Submit</div>
</div>

子组件形式:

<div class="fields-wrap" [formGroup]="child">
<input type="text" formControlName="firstname" />
<input type="text" formControlName="lastname" />
<input type="text" formControlName="email" />
</div>

当我从父组件单击提交时如何获取这些子值。谁能帮我?

标签: angularangular-reactive-forms

解决方案


Form而不是作为@Input()你可以使用的传递viewProviders,我发现它阅读起来更干净。

要做到这一点非常简单,在您的子组件打字稿文件中,您只需向您的@Component

viewProviders: [ { provide: ControlContainer, useExisting: FormGroupDirective }]

所以总的来说它会输出如下:

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss'],
  viewProviders: [ { provide: ControlContainer, useExisting: FormGroupDirective }]
})

stackblitz 示例:https ://stackblitz.com/edit/angular-ruxfee


推荐阅读