问题描述
您好我有具有子组件的组件(父)。并且在孩子component.I形式要提交由父component.I形式正在试图调用从父组件的子组件的功能,但我不successful.I作出这里plunker演示的
这就是我如何调用父组件的功能
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=previewThis is how i am calling the function in Parent component
childcmp:App;
constructor(fb: FormBuilder){
this.childcmp=new App(fb);
}
submit(){
this.childcmp.onSubmit();
}
这是子组件我的code
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);
}
我能够提交,但值我没有得到correctly.Somebody请帮我
I am able to submit but values i am not getting correctly.Somebody please help me
推荐答案
您需要利用 @ViewChild
装饰通过注射从父一个中引用的子组件:
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();
}
}
下面是更新plunkr:。
Here is the updated plunkr: http://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt?p=preview.
您可以看到, @Query
参数装饰也可以使用:
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
这篇关于如何提交从父组件的形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!