【发布时间】:2019-03-19 04:00:06
【问题描述】:
我是 Reactive Forms 的新手,我习惯使用模板驱动的表单。
我在这里学习教程:https://angular-templates.io/tutorials/about/angular-forms-and-validations
我有一个用户类:
export class User {
public pseudo: string;
public email: string;
public password: string;
public constructor(init?: User) {
Object.assign(this, init);
}
}
我在一个组件中得到了我的 FormGroups:
this.matching_passwords_group = new FormGroup(
{
password: new FormControl(
'',
Validators.compose([
Validators.minLength(5),
Validators.required,
Validators.pattern(
'^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]+$'
)
])
),
confirm_password: new FormControl('')
},
(formGroup: FormGroup) => {
return PasswordValidator.areEqual(formGroup);
}
);
// user details form validations
this.userDetailsForm = this.fb.group({
pseudo: new FormControl('', Validators.required),
email: new FormControl(
'',
Validators.compose([
Validators.required,
Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
])
),
matching_passwords: this.matching_passwords_group,
terms: new FormControl(false, Validators.pattern('true'))
});
}
如您所见,有一个嵌套的formGroup 用于密码确认(检查两个密码是否相等)。
然后,当用户单击提交时,我想将我的 formGroup 值转换为我的用户对象。
我遵循了这里的建议:Reactive Forms correctly convert Form Value to Model Object
这里是我的提交方法:
onSubmitUserDetails(value) {
this.newUser = new User(this.userDetailsForm.value);
}
但显然,使用嵌套密码formGroup 我没有this.newUser 中需要的内容:
{电子邮件:“test@test”matching_passwords:{密码:“Test1”, Confirm_password:“Test1”} 伪:“test” 术语:true}
我可以一一设置值,但对于较大的表单可能会很长。有什么方便的方法可以将formGroup 值设置为一个类并解决嵌套密码formGroup 的问题?我们应该如何实现这一目标?
最好的解决方案是让我的 User 对象准确反映 formGroups 结构,然后在我将对象发送到 API 时排除无用字段(如密码确认)?
另外,如果我的 User 类中有一个嵌套对象,比如说书籍集合,我应该如何转换嵌套的 FormGroups 以匹配类结构?
【问题讨论】:
-
这里的
pseudo是什么?它也与您的User课程中的login相同吗? -
对不起,我编辑了我的帖子,但是是一样的^^
-
嗯,创建具有表单值的类并没有什么神奇之处,除了提取相关的属性值并在构造函数中处理它们。同样,例如,如果您有嵌套对象并且在表单中也有它们,您应该提取它们并将它们传递给构造函数。例如:
const { user, pass, email } = this.formGroup.value; const user = new User({ user,pass,email });
标签: angular typescript angular-reactive-forms