Angular 2 – 无法设置表单数组值

我收到此错误:

There are no form controls registered with this array yet. If you’re using ngModel, you may want to check next tick (e.g. use setTimeout).

使用此代码时:

public settingsForm: FormGroup = this.fb.group({
  collaborators: this.fb.array([]),
  rsvp: this.fb.group({
    latestDate: ['', [Validators.required]],
    latestTime: ['', [Validators.required]],
    guestLimit: ['', [Validators.required]],
    isRSVPOpen: false,
    isGuestPlusOne: false,
    isAutoApproveToGuestlist: false,
    isOnlyFacebookRSVP: false,
    isBirthdayAndPhoneRequired: false
  }),
  tickets: this.fb.group({
    info: this.fb.group({
      closingDate: '',
      closingTime: ''
    }),
    types: this.fb.array([])
  })
});

在ngOnInit里面:

this.eventSubscription = this.af.database.object('/events/' + this.eventId)
  .filter(event => event['$value'] !== null)
  .subscribe((event: IEvent) => {

    const settings: ISettings = event.settings;
    const collaborators: ICollaborator[] = settings.collaborators;
    const rsvp: IRSVP = settings.rsvp;
    const tickets: ITickets = settings.tickets;

    this.settingsForm.setValue({
      collaborators: collaborators || [],
      rsvp: rsvp,
      tickets: {
        info: tickets.info,
        types: tickets.types || []
      }
    });
  }
);

当协作者包含一个值时,即它不是未定义的,null或为空[],类似于:

[
  {
    email: 'foo@bar.com',
    role: 1
  },
  {
    email: 'baz@bar.com',
    role: 2
  }
]

然后应用程序在eventSubscription中的setValue行崩溃.

我无法弄清楚为什么会这样.

有任何想法吗?

最佳答案 使用控件初始化表单数组.这将解决问题.如果您需要知道如何操作,请参阅 Reactive Forms指南.如果您使用的是ngModel,那么删除它可能是值得的.

点赞