如何提交从父组件的形式? [英] How to submit the form from parent component?

查看:146
本文介绍了如何提交从父组件的形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有具有子组件的组件(父)。并且在孩子component.I形式要提交由父component.I形式正在试图调用从父组件的子组件的功能,但我不successful.I作出这里plunker演示的 http://plnkr.co/edit/TnkLK2FffAPP1YVo0uOg?p=$p$pview
这就是我如何调用父组件的功能

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();
}

这是子组件我的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: http://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt p = preVIEW

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

这篇关于如何提交从父组件的形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆