angular reactive form: pass child component value to parent component

我怕爱的太早我们不能终老 提交于 2019-12-04 02:32:14

问题


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?


回答1:


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




回答2:


Just define the form in the parent component.ts and pass it to the child with data-binding. The parent will keep track of the form value. Example : https://stackblitz.com/edit/formreset?file=src%2Fapp%2Fapp.component.html



来源:https://stackoverflow.com/questions/53052855/angular-reactive-form-pass-child-component-value-to-parent-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!