以编程方式设置表单的字段使表单无效
Programmatically set form's fields keeps the form invalid
在 Ionic 3 / Angular 5 应用程序中,我有一个由 3 个字段组成的表单:
- 名字(输入文本)
- 生日(日期时间选择器)
- 头像(单选按钮)
如果表单无效,提交按钮将被禁用:
[disabled]="!addChildForm.valid"
在初始时,我会检查用户是在创建一个新的 child 还是在编辑一个。我编辑,我以编程方式填充字段。
这工作正常,但提交按钮处于非活动状态。尽管生日填满了,但我必须单击它才能打开(和关闭)选择器以启用提交按钮。
我的代码:
createForm(child?: Child): void {
this.addChildForm = this.formBuilder.group({
firstnameInput: ['', Validators.required],
birthdateInput: ['', Validators.required],
avatarInput: ['', Validators.required]
});
// If we are editing a child, populate the form
if (child) {
this.addChildForm.setValue({
firstnameInput: child.firstname,
birthdateInput: moment(child.birthdate).format(),
avatarInput: child.avatar
});
}
}
知道如何以某种方式强制表单在填充表单后进行检查以启用提交按钮吗?
不是构建表单然后然后用数据填充它,而是在构建步骤中进行检查并一次性完成。像这样:
createForm(child?: Child): void {
this.addChildForm = this.formBuilder.group({
firstnameInput: [child ? child.firstname : '', Validators.required],
birthdateInput: [child ? moment(child.birthdate).format() : '', Validators.required],
avatarInput: [child ? child.avatar : '', Validators.required]
});
}
这是一个带有工作示例的 link:https://stackblitz.com/edit/angular-ygaoz7。
尝试将示例中 this.child
的初始值更改为空字符串,您将看到表单发生变化并且提交按钮被禁用。当它们都有值时,按钮将再次启用。
在 Ionic 3 / Angular 5 应用程序中,我有一个由 3 个字段组成的表单:
- 名字(输入文本)
- 生日(日期时间选择器)
- 头像(单选按钮)
如果表单无效,提交按钮将被禁用:
[disabled]="!addChildForm.valid"
在初始时,我会检查用户是在创建一个新的 child 还是在编辑一个。我编辑,我以编程方式填充字段。 这工作正常,但提交按钮处于非活动状态。尽管生日填满了,但我必须单击它才能打开(和关闭)选择器以启用提交按钮。
我的代码:
createForm(child?: Child): void {
this.addChildForm = this.formBuilder.group({
firstnameInput: ['', Validators.required],
birthdateInput: ['', Validators.required],
avatarInput: ['', Validators.required]
});
// If we are editing a child, populate the form
if (child) {
this.addChildForm.setValue({
firstnameInput: child.firstname,
birthdateInput: moment(child.birthdate).format(),
avatarInput: child.avatar
});
}
}
知道如何以某种方式强制表单在填充表单后进行检查以启用提交按钮吗?
不是构建表单然后然后用数据填充它,而是在构建步骤中进行检查并一次性完成。像这样:
createForm(child?: Child): void {
this.addChildForm = this.formBuilder.group({
firstnameInput: [child ? child.firstname : '', Validators.required],
birthdateInput: [child ? moment(child.birthdate).format() : '', Validators.required],
avatarInput: [child ? child.avatar : '', Validators.required]
});
}
这是一个带有工作示例的 link:https://stackblitz.com/edit/angular-ygaoz7。
尝试将示例中 this.child
的初始值更改为空字符串,您将看到表单发生变化并且提交按钮被禁用。当它们都有值时,按钮将再次启用。