问题描述
有没有一种方法可以在现有数据模型的基础上使用所有验证魔术来创建反应形式.在下面的示例中,作者将整个新对象传递给formbuilder,但是我想要实现的是一种优雅的方式来告诉formbuilder哪些字段是必需字段或需要其他验证.
https://malcoded.com/posts/angular-fundamentals-reactive-forms
export class PersonalData {
email: string = '';
mobile: string = '';
country: string = '';
}
...
createFormGroupWithBuilderAndModel(formBuilder: FormBuilder) {
return formBuilder.group({
personalData: formBuilder.group(new PersonalData()),
requestType: '',
text: ''
});
}
我只想跳过为模型中的每个字段分配FormControl的过程.
@EDIT
经过一些研究和@ xrobert35的一点提示,我想尝试并使用 https://www.npmjs.com/package/@rxweb/reactive-form-validators
它们可能是很多"做您想做的事情的方法,但是只是扩展了您的实际解决方案:您的个人数据可能看起来像:
export class PersonalData {
email: string = ['', Validators.required];
mobile: string = ['', Validators.required, Validators.maxLength(10)];
country: string = '';
}
is there a way to create a reactive form basing on an existing data model with all the validation magic. In the example below author passes whole new object into a formbuilder but what I want to achieve is elegant way to tell formbuilder what field is required or needs some other validation.
https://malcoded.com/posts/angular-fundamentals-reactive-forms
export class PersonalData {
email: string = '';
mobile: string = '';
country: string = '';
}
...
createFormGroupWithBuilderAndModel(formBuilder: FormBuilder) {
return formBuilder.group({
personalData: formBuilder.group(new PersonalData()),
requestType: '',
text: ''
});
}
I just want to skip the process of assigning a FormControl for each field in the model.
@EDIT
After some research and little hint from @xrobert35 I wanted to try and used https://www.npmjs.com/package/@rxweb/reactive-form-validators
They could be "many" way to do what you want to do, but by just extending your actual solution : Your personnal data could look like :
export class PersonalData {
email: string = ['', Validators.required];
mobile: string = ['', Validators.required, Validators.maxLength(10)];
country: string = '';
}
这篇关于基于带有验证的模型的角反应形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!