abhilash reddy
abhilash reddy

Reputation: 1586

Why is that i can't inject the child component values into parent component?

Hie...I am having a child component which has form.I am trying to inject the form values of child into parent. I am getting the control group but i am not able to get the values.I have made a plunker demo here http://plnkr.co/edit/I5feR6NHdQuTT7rJrVYA?p=preview

onSubmit(value) {
console.log(this.app.addressForm.value);
console.log('you submitted value: ', value);  
}

This is how i am getting the value of child form i have mentioned the providers in Parent component...Somebody please tell me how to get the form values of child component when something is entered into it?

Upvotes: 1

Views: 504

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202316

After having a look at your plunkr, I see several possibilities here:

  • You can directly reference child component like the Address one using the ViewChild annotation. See this answer Angular2 : No provider for String! (child -> String) in [Array in parent

    @Component({
      (...)
    })
    export class AppComponent {
      @ViewChild(Address)
      address:Address; // your app property
      (...)
    }
    

    You can use the address property when you click on the submit button to have access to the addressForm property of the Address component.

  • Do you want to define and manage all controls within your AppComponent. If so it will be possible to pass them as parameter of your Address component. This way you will work by reference so your parent component will know the value when clicking on the submit button. Something like that:

    @Component({
      (...)
    })
    export class Address{
      @Input()
      address1Ctrl:Control;
      @Input()
      cityCtrl:Control;
    
      constructor() {
        // No need to configure controls here
      }
    }
    
    @Component({
      (...)
      template: `
        (...)
        <address [address1Ctrl]="myForm.controls.address1"
                 [cityCtrl]="myForm.controls.address1"></address>
        (...)
      `
    })
    export class AppComponent {
      constructor(fb: FormBuilder) {  
        this.myForm = fb.group({  
         'name':  ['', Validators.required],
         'address1':  new Control('',Validators.required),
         'city':new Control('',Validators.required)
         'Phone':  ['', Validators.required]
        });
    }
    
  • The last option is to implement a NgForm / NgControl compliant component. It's a bit more advanced approach. See this answer for more details: Angular 2 custom form input

I refactored your plunkr with the first approach. See this new plunkr: http://plnkr.co/edit/sTEU4Fz7b7TXtRo1LXgK?p=preview.

Upvotes: 3

Related Questions