2017-04-04 67 views
0

Angular2:我創建這個表格嵌套表格組

this.cardForm = this.fb.group({ 
    number: ['', Validators.compose([Validators.required, this.validateCardNumber])], 
    holderName: ['', Validators.required], 
    expiry: this.fb.group({ 
     expirationMonth: ['', Validators.required], 
     expirationYear: ['', Validators.required], 
    }), 

正如你所看到的,我創建了一個名爲expiry嵌套表格組。到我的模板:

<form [formGroup]="cardForm" novalidate="novalidate" (ngSubmit)="onSave()"> 
    <div class="form-group"> 
    <label for="cardnumber">Card number</label> 
    <input 
     type="text" 
     formControlName="number" 
     placeholder="Card number" 
     name="cardnumber" 
     class="input-transparent form-control"> 
    </div> 
    ... 
    <div class="form-group" formGroupName="expiry"> 
    <label for="expirationmonth">Expiration month</label> 
    <select2 id="default-select" 
     name="expirationmonth" 
     [data]="months$ | async" 
     [width]="250" 
     [options]="select2Options"> 
    </select2> 

    <label for="expirationyear">Expiration year</label> 
    <select2 id="default-select2" 
     name="expirationyear" 
     [data]="years$ | async" 
     [width]="250" 
     [options]="select2Options"> 
    </select2> 
    </div> 

我得到這個錯誤:

ERROR Error: formGroup expects a FormGroup instance. Please pass one in. 

    Example: 


<div [formGroup]="myGroup"> 
    <input formControlName="firstName"> 
</div> 

In your class: 

this.myGroup = new FormGroup({ 
    firstName: new FormControl() 
}); 

任何想法?

+0

,我們需要更多的代碼,如果是'this.cardForm = this.fb.group( ...)叫? – n00dl3

+0

爲select2組件添加代碼 – yurzui

+0

@ n00dl3,它在構造函數的組件上調用。 – Jordi

回答

3

在您的組件端設置了this.cardForm之前,您的視圖正在加載。

儘量把*ngIf

<form *ngIf="cardForm" [formGroup]="cardForm" novalidate="novalidate" (ngSubmit)="onSave()"> 

或者嘗試在一個div來封裝與*ngIf

<div *ngIf="cardForm"> 
    <form [formGroup]="cardForm" novalidate="novalidate" (ngSubmit)="onSave()"> 

    </form> 
    </div> 
+6

或在正確的時間初始化您的表單:D! – n00dl3

+1

我已經初始化成了'ngOnInit'。它現在有效。 – Jordi