Angular2:未获取表单值

时间:2017-04-06 12:03:46

标签: angular angular2-forms

我已在ngOnInit()方法中创建了此表单:

this.cardForm = this.fb.group({
    card_number: ['', Validators.required],
    holderName: ['', Validators.required],
    expiry: ['', Validators.required],
    cvc: ['', Validators.required],
    address_line1: ['', Validators.required],
    address_line2: ['', Validators.required],
    address_city: ['', Validators.required],
    address_state: ['', Validators.required],
    address_zip: ['', Validators.required],
    address_country: ['', Validators.required]
  });

在我的模板上:

<form [formGroup]="cardForm" novalidate="novalidate">
  <div class="form-group">
    <label for="cardnumber">Card number</label>
    <input 
      type="text"
      name="cardnumber"
      class="input-transparent form-control"
      formControlName="card_number"
      data-mask="9999-9999-9999-9999"
      placeholder="____-____-____-____"
      required="required">
 </div>

当我尝试获取此表单的值时,card_numbercvcexpiry为空。

enter image description here

如您所见,cardForm有几个字段。我已经说过它们在模板上的两个<from>标签中绑定了。

因此,card_number, holderName, expiry and cvc在第一张表格中绑定:

<form [formGroup]="cardForm" novalidate="novalidate">
  <input 
    id="card_number"
    type="text"
    name="card_number"
    class="input-transparent form-control"
    formControlName="card_number"...

和其他标记在第二个<form>标记上绑定:

<form [formGroup]="cardForm" novalidate="novalidate">
  <input 
    id="address_line1"
    type="text"
    name="address_line1"
    class="input-transparent form-control"
    formControlName="address_line1"...

我还试图创建两个formGroup,并将它们绑定到模板上的每个表单:

this.cardForm = this.fb.group({
    card_number: ['', Validators.required],
    holderName: ['', Validators.required],
    expiry: ['', Validators.required],
    cvc: ['', Validators.required]
});
this.detailsForm = this.fb.group({
    address_line1: ['', Validators.required],
    address_line2: ['', Validators.required],
    address_city: ['', Validators.required],
    address_state: ['', Validators.required],
    address_zip: ['', Validators.required],
    address_country: ['', Validators.required]
  });

在模板上:

<form [formGroup]="cardForm" novalidate="novalidate">
<form [formGroup]="detailsForm" novalidate="novalidate">

尽管如此:

enter image description here

1 个答案:

答案 0 :(得分:0)

对于类似的情况,我使用了该特定表单组对象的patchValuesetValue

例如ngOnInit中你可以设置:

 this.cardForm.patchValue({card_number: 'foobar'}); 

同样,如果值发生变化,您可以以类似的方式更新。

cardDetailsChanged(val){
   this.cardForm.patchValue({card_number: val});
}