【问题标题】:Angular 2 - Creating form in a subscription causes crash saying the formGroup is undefinedAngular 2 - 在订阅中创建表单会导致崩溃,说 formGroup 未定义
【发布时间】:2017-06-24 18:29:27
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    使用*ngIf="settingsForm"

    如果您有一个尚未初始化的 FormGroup,则不能在模板中使用它。例如,如果 settingsForm 尚未初始化,则以下内容将不起作用:

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

    改为这样做:

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

    【讨论】:

      猜你喜欢
      • 2017-06-19
      • 1970-01-01
      • 2020-07-06
      • 2019-09-02
      • 2013-05-13
      • 2017-03-17
      • 1970-01-01
      • 2016-09-30
      • 2017-10-06
      相关资源
      最近更新 更多