角度反应形式:将子组件值传递给父组件 [英] angular reactive form: pass child component value to parent component

查看:68
本文介绍了角度反应形式:将子组件值传递给父组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

示例父表单:

<div class="input-wrap"><子组件></子组件>

<输入类型按钮">提交</div>

子组件形式:

<input type="text" formControlName="firstname"/><input type="text" formControlName="lastname"/><input type="text" formControlName="email"/>

当我从父组件单击提交时如何获取这些子值.有人可以帮我吗?

解决方案

您可以使用 viewProviders<,而不是将 Form 作为 @Input() 传入/code>,我觉得它读起来更清晰.

要做到这一点非常简单,在您的子组件打字稿文件中,您只需要将一个属性添加到您的 @Component

viewProviders: [ { 提供: ControlContainer, useExisting: FormGroupDirective }]

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

@Component({选择器:'app-child',templateUrl: './child.component.html',styleUrls: ['./child.component.scss'],viewProviders: [ { 提供: ControlContainer, useExisting: FormGroupDirective }]})

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

im implementing reactive-form in angular. im unable to pass value from child to parent.

example parent form:

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

Child componet form:

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

how to get these child value when i click submit from parent component. can anyone help me?

解决方案

Instead of passing in Form as an @Input() you can use viewProviders which I find it a lot more cleaner to read.

To do this is very simple, in your child component typescript file you just need to add one property to your @Component

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

So all together it would output like this:

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

Example on stackblitz: https://stackblitz.com/edit/angular-ruxfee

这篇关于角度反应形式:将子组件值传递给父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆