【问题标题】:Why is that i can't inject the child component values into parent component?为什么我不能将子组件值注入父组件?
【发布时间】:2016-05-15 15:45:57
【问题描述】:

您好...我有一个具有表单的子组件。我正在尝试将子组件的表单值注入父组件。我得到了控制组,但我无法获得值。我在这里做了一个 plunker 演示 http://plnkr.co/edit/I5feR6NHdQuTT7rJrVYA?p=preview

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

这就是我获取子表单值的方式,我在父组件中提到了提供者...有人请告诉我当输入内容时如何获取子组件的表单值?

【问题讨论】:

    标签: angular


    【解决方案1】:

    查看您的 plunkr 后,我在这里看到了几种可能性:

    • 您可以使用ViewChild 注释直接引用Address 之类的子组件。看到这个答案Angular2 : No provider for String! (child -> String) in [Array in parent

      @Component({
        (...)
      })
      export class AppComponent {
        @ViewChild(Address)
        address:Address; // your app property
        (...)
      }
      

      您可以在单击提交按钮时使用address 属性来访问Address 组件的addressForm 属性。

    • 您想在AppComponent 中定义和管理所有控件吗?如果是这样,则可以将它们作为Address 组件的参数传递。这样,您将通过引用工作,以便您的父组件在单击提交按钮时知道该值。类似的东西:

      @Component({
        (...)
      })
      export class Address{
        @Input()
        address1Ctrl:Control;
        @Input()
        cityCtrl:Control;
      
        constructor() {
          // No need to configure controls here
        }
      }
      
      @Component({
        (...)
        template: `
          (...)
          <address [address1Ctrl]="myForm.controls.address1"
                   [cityCtrl]="myForm.controls.address1"></address>
          (...)
        `
      })
      export class AppComponent {
        constructor(fb: FormBuilder) {  
          this.myForm = fb.group({  
           'name':  ['', Validators.required],
           'address1':  new Control('',Validators.required),
           'city':new Control('',Validators.required)
           'Phone':  ['', Validators.required]
          });
      }
      
    • 最后一个选项是实现NgForm / NgControl 兼容组件。这是一种更高级的方法。有关详细信息,请参阅此答案:Angular 2 custom form input

    我用第一种方法重构了你的 plunkr。看到这个新的 plunkr:http://plnkr.co/edit/sTEU4Fz7b7TXtRo1LXgK?p=preview。

    【讨论】:

      猜你喜欢
      • 2016-04-05
      • 2019-02-24
      • 1970-01-01
      • 2022-07-25
      • 2017-05-18
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      相关资源
      最近更新 更多