0

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 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

3 Comments

I like this approach. What if address FormGroup needs to be created in the address.component? Does this idea somehow apply to this situation?
You mean you want the address: this.formBuilder.group({...}) inside address.component.ts? Not sure if possible unless somehow you are able to get reference of the form, could be through @Input? I haven't tried if you are doing that then no point of doing this method. Ideally you want your components to be dumb as possible and have your main component act as a "container" which handles events from the dumb component. Making component architecture reusable.
It actually works via @Input, so it seems that I will stick to this solution, thx.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.