Search code examples
angulartypescriptangular2-formsangular2-formbuilderangular-reactive-forms

Angular 2 - Can't set form array value


I get this error:

There are no form controls registered with this array yet. If you're using ngModel, you may want to check next tick (e.g. use setTimeout).

When using this code:

public settingsForm: FormGroup = this.fb.group({
  collaborators: this.fb.array([]),
  rsvp: this.fb.group({
    latestDate: ['', [Validators.required]],
    latestTime: ['', [Validators.required]],
    guestLimit: ['', [Validators.required]],
    isRSVPOpen: false,
    isGuestPlusOne: false,
    isAutoApproveToGuestlist: false,
    isOnlyFacebookRSVP: false,
    isBirthdayAndPhoneRequired: false
  }),
  tickets: this.fb.group({
    info: this.fb.group({
      closingDate: '',
      closingTime: ''
    }),
    types: this.fb.array([])
  })
});

Inside ngOnInit:

this.eventSubscription = this.af.database.object('/events/' + this.eventId)
  .filter(event => event['$value'] !== null)
  .subscribe((event: IEvent) => {

    const settings: ISettings = event.settings;
    const collaborators: ICollaborator[] = settings.collaborators;
    const rsvp: IRSVP = settings.rsvp;
    const tickets: ITickets = settings.tickets;

    this.settingsForm.setValue({
      collaborators: collaborators || [],
      rsvp: rsvp,
      tickets: {
        info: tickets.info,
        types: tickets.types || []
      }
    });
  }
);

When collaborators contains a value, i.e it's not undefined, null or empty [], something like:

[
  {
    email: '[email protected]',
    role: 1
  },
  {
    email: '[email protected]',
    role: 2
  }
]

Then the app crashes on the setValue line in the eventSubscription.

I cannot figure out why this is happening.

Any ideas?


Solution

  • Initialize the form array with the control. That would resolve the issue. See Reactive Forms guide if you need to know how to do that. If you are using ngModel it would probably worth to remove it.