问题
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