1

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?

4
  • we need more code, when is this.cardForm = this.fb.group(...) called ? Commented Apr 4, 2017 at 9:24
  • Add code for select2 component Commented Apr 4, 2017 at 9:25
  • @n00dl3, it's called on constructor's component. Commented Apr 4, 2017 at 9:26
  • 1
    @yurzui. You can find documentation here. Commented Apr 4, 2017 at 9:27

1 Answer 1

6

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>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.