Angular 2 - Creating form in a subscription causes crash saying the formGroup is undefined

心已入冬 提交于 2019-12-11 09:23:29

问题


I've got some data in my Firebase database, this data I want to apply to a form via FormBuilder. It works somewhat good but I get errors more often than not saying formGroup expects a FormGroup instance. Please pass one in..

What doesn't make sense is that when I apply new changes to the database which cause the subscription to fire, I get the error. Despite this.settingsForm being set before and after the subscription runs after updating.

Here's the subscription:

this.eventSubscription = this.af.database.object('/events/' + this.eventId).subscribe(
  (event: IEvent) => {

    const rsvp: IRSVP = event.rsvp;
    const settings: ISettings = event.settings;
    const tickets: ITickets = event.tickets;

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

So what I'm wondering is why is this happening and how can I prevent it? Can't I init the form like this?


回答1:


Use *ngIf="settingsForm".

If you have a FormGroup that has not been initialized, it cannot be used in the template. For example, the following will not work if settingsForm has not been initialized:

<form [formGroup]="settingsForm ">
  <input formControlName="name" />
</form>

Do this instead:

<form *ngIf="settingsForm" [formGroup]="settingsForm ">
  <input formControlName="name" />
</form>


来源:https://stackoverflow.com/questions/42091090/angular-2-creating-form-in-a-subscription-causes-crash-saying-the-formgroup-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!