【问题标题】:How to get the form values of parent component along with child component?如何获取父组件和子组件的表单值?
【发布时间】:2016-06-25 08:32:51
【问题描述】:

我有一个模型驱动形式的子组件(地址信息)和父组件(基本信息)......当单击“提交”按钮时,请有人帮我获取如下所述的数据。 ....plunker 演示 http://plnkr.co/edit/ZKPTrP2bGmKZkElShGj0?p=preview

submitted value: 
{
"firstname": "",
"lastname": "",
"addressinfo":{
   "Line1":"",
   "Line2":"",
 }
}

我不想在我的子窗体中使用 ngmodel...有人帮我找到获得这个的方法

【问题讨论】:

    标签: angular


    【解决方案1】:

    你需要在父子中为addressinfo创建一个空组:

    this.myForm = fb.group({  
      'firstname':  ['', Validators.required],
      'lastname':  ['', Validators.required]  
      'addressinfo': fb.group()
    });
    

    那么你需要把这个组控件传递给子组件:

    <child [control]="myForm.controls.addressinfo"></child>
    

    在子组件中,你需要为这个控件添加一个输入,并创建与你的Line*字段对应的子控件:

    @Component({ ... })
    export class ChildComp {  
      @Input()
      control:Control;
    
      ngOnInit() {
        this.control.addControl('Line1', new Control('', Validators.required));
        this.control.addControl('Line2', new Control('', Validators.required));
      }
    }
    

    最后,您可以将这些子控件附加到子组件中的输入上:

    <div class="field">  
      <label>Line1</label>  
      <input type="text" [ngFormControl]="control.controls['Line1']">
    </div>
    
    <div class="field">  
      <label>Line2</label>  
      <input type="text" [ngFormControl]="control.controls['Line2']">
    </div>
    

    这是更新的 plunkr:http://plnkr.co/edit/Bigo3DNnLTixW9ONry1e?p=preview

    【讨论】:

      猜你喜欢
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-08
      • 2018-03-18
      相关资源
      最近更新 更多