角度2-无法设置表单数组值 [英] Angular 2 - Can't set form array value
问题描述
我收到此错误:
此表单尚未注册任何窗体控件。如果您使用的是ngModel,则可能需要检查下一个刻度(例如,使用setTimeout)。
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 || []
}
});
}
);
当合作者
包含一个值时,即不是 undefined
, null
或空的 []
,类似:
When collaborators
contains a value, i.e it's not undefined
, null
or empty []
, something like:
[
{
email: 'foo@bar.com',
role: 1
},
{
email: 'baz@bar.com',
role: 2
}
]
然后该应用程序在<$ c $中的 setValue
行崩溃c> eventSubscription 。
Then the app crashes on the setValue
line in the eventSubscription
.
我不知道为什么会这样。
I cannot figure out why this is happening.
有什么想法吗?
推荐答案
使用控件初始化表单数组。这样可以解决问题。如果您需要了解如何操作,请参见反应形式指南那。如果您使用的是 ngModel
,则可能值得删除它。
Initialize the form array with the control. That would resolve the issue. See Reactive Forms guide if you need to know how to do that. If you are using ngModel
it would probably worth to remove it.
这篇关于角度2-无法设置表单数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!