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