Angular 2 - 在订阅中创建表单会导致崩溃,说 formGroup 未定义 [英] Angular 2 - Creating form in a subscription causes crash saying the formGroup is undefined

查看:20
本文介绍了Angular 2 - 在订阅中创建表单会导致崩溃,说 formGroup 未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆