Angular 2 - 在订阅中创建表单导致崩溃,表示formGroup未定义

时间:2017-02-07 13:27:25

标签: angular firebase rxjs angular2-forms angular2-formbuilder

我的Firebase数据库中有一些数据,我希望通过FormBuilder将这些数据应用于表单。它的效果有点好,但我经常会遇到错误而不是formGroup expects a FormGroup instance. Please pass one in.

没有意义的是,当我对数据库应用新的更改导致订阅触发时,我收到错误。尽管在更新后运行订阅之前和之后设置了this.settingsForm

这是订阅:

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 || [])
      })
    });
  }
);

所以我想知道为什么会发生这种情况,我该如何预防呢?我不能像这样初始化表格吗?

1 个答案:

答案 0 :(得分:1)

使用delete tmp3;

如果您有一个尚未初始化的FormGroup,则无法在模板中使用它。例如,如果*ngIf="settingsForm"尚未初始化,则以下内容无效:

settingsForm

请改为:

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