Angular 2-在订阅中创建表单会导致崩溃,提示未定义formGroup [英] Angular 2 - Creating form in a subscription causes crash saying the formGroup is undefined
问题描述
我的Firebase数据库中有一些数据,这些数据我想通过 FormBuilder
应用于表单。它工作得有些好,但是我经常会出错,而不是说 formGroup需要FormGroup实例。请传递一个。
。
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.
.
没有意义的是,当我对数据库应用导致订阅被触发的新更改时,出现错误。尽管在更新后订阅运行之前和之后都设置了 this.settingsForm
。
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.
以下是订阅:
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?
推荐答案
使用 * ngIf = settingsForm
。
如果您有尚未初始化的FormGroup,则无法在模板中使用它。例如,如果尚未初始化 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>
执行以下操作:
<form *ngIf="settingsForm" [formGroup]="settingsForm ">
<input formControlName="name" />
</form>
这篇关于Angular 2-在订阅中创建表单会导致崩溃,提示未定义formGroup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!