【问题标题】:How to submit the form from parent component?如何从父组件提交表单?
【发布时间】:2016-01-30 10:33:10
【问题描述】:

嗨,我有一个组件(父组件),它有一个子组件。子组件中有一个表单。我想从父组件提交表单。我试图从父组件调用子组件中的一个函数,但我没有成功。我在这里做了一个 plunker 演示http://plnkr.co/edit/TnkLK2FffAPP1YVo0uOg?p=preview 这就是我在父组件中调用函数的方式

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

我可以提交,但我的值不正确。有人请帮助我

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

    您需要利用@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();
      }
    
      (...)
    }
    

    希望对你有帮助, 蒂埃里

    【讨论】:

      猜你喜欢
      • 2019-12-11
      • 2020-07-15
      • 2019-05-04
      • 2021-07-28
      • 2018-05-04
      • 2017-11-01
      • 2019-01-03
      • 2019-05-16
      • 1970-01-01
      相关资源
      最近更新 更多