1
votes

I've created this form:

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],
    }),

As you can see, I've created a nested form group named expiry. Into my template:

<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>

I'm getting this error:

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

Any ideas?

1
we need more code, when is this.cardForm = this.fb.group(...) called ? - n00dl3
Add code for select2 component - yurzui
@n00dl3, it's called on constructor's component. - Jordi
@yurzui. You can find documentation here. - Jordi

1 Answers

6
votes

Your view is getting loaded before your this.cardForm is set in your component side.

Try to put *ngIf:

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

Or try to encapsulate in a div with *ngIf:

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

    </form>
   </div>