2
votes

Hi i have a component(parent) which has a child component. And there is a form in child component.I want to submit the form from parent component.I am trying to call a function in child component from parent component but i am not successful.I have made a plunker demo here http://plnkr.co/edit/TnkLK2FffAPP1YVo0uOg?p=preview This is how i am calling the function in Parent component

  childcmp:App;
constructor(fb: FormBuilder){
this.childcmp=new App(fb);
}
submit(){
this.childcmp.onSubmit();
}

And this is my code in child component

myForm: ControlGroup;

constructor(fb: FormBuilder) {  
this.myForm = fb.group({  
  'sku':  ['', Validators.required]  
});  
}

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

I am able to submit but values i am not getting correctly.Somebody please help me

1

1 Answers

7
votes

You need to leverage the @ViewChild decorator to reference the child component from the parent one by injection:

import { Component, ViewChild } from 'angular2/core';  

(...)

@Component({
  selector: 'my-app',
  template: `
    <h1>My First Angular 2 App</h1>
    <child></child>
    <button (click)="submit()">Submit</button>
  `,
  directives:[App]
})
export class AppComponent { 
  @ViewChild(App) childcmp:App;

  (...)

  submit(){
    this.childcmp.onSubmit();
  }
}

Here is the updated plunkr: http://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt?p=preview.

You can notice that the @Query parameter decorator could also be used:

export class AppComponent { 
  constructor(@Query(App) children:QueryList<App>) {
    this.childcmp = children.first();
  }

  (...)
}

Hope it helps you, Thierry