嗨我有一个组件(父)有一个子组件。 并且在子组件中有一个表单。我想从父组件提交表单。我试图从父组件调用子组件中的函数但是我没有成功。我在这里做了一个plunker演示http:// plnkr .co / edit / TnkLK2FffAPP1YVo0uOg?p =预览这就是我在父组件中调用函数的方法
childcmp:App; constructor(fb: FormBuilder){ this.childcmp=new App(fb); } submit(){ this.childcmp.onSubmit(); }这是我在子组件中的代码
myForm: ControlGroup; constructor(fb: FormBuilder) { this.myForm = fb.group({ 'sku': ['', Validators.required] }); } onSubmit(){ console.log('you submitted value: ', this.myForm.value); }我能够提交,但我没有得到正确的价值。有人请帮助我
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
最满意答案
您需要利用@ViewChild装饰器通过注入引用父组件中的子组件:
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(); } }这是更新的plunkr: http ://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt?p = preview。
您可以注意到也可以使用@Query参数装饰器:
export class AppComponent { constructor(@Query(App) children:QueryList<App>) { this.childcmp = children.first(); } (...) }希望它对你有帮助,蒂埃里
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
更多推荐
发布评论