基于带验证模型的角度反应形式 [英] Angular reactive form based on model with validation

查看:26
本文介绍了基于带验证模型的角度反应形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法基于现有的数据模型创建一个具有所有验证魔法的反应式表单.在下面的示例中,作者将全新的对象传递到 formbuilder 中,但我想要实现的是一种优雅的方式来告诉 formbuilder 需要哪些字段或需要其他一些验证.>

https://malcoded.com/posts/angular-fundamentals-reactive-forms

导出类 PersonalData {电子邮件:字符串 = '';手机:字符串 = '';国家:字符串 = '';}...createFormGroupWithBuilderAndModel(formBuilder: FormBuilder) {返回 formBuilder.group({个人数据:formBuilder.group(new PersonalData()),请求类型: '',文本: ''});}

我只想跳过为模型中的每个字段分配 FormControl 的过程.

@EDIT

经过@xrobert35 的一些研究和一点提示后,我想尝试使用 https://www.npmjs.com/package/@rxweb/reactive-form-validators

解决方案

它们可以是多种"方式来完成您想做的事情,但只需扩展您的实际解决方案:您的个人数据可能如下所示:

导出类 PersonalData {电子邮件:字符串 = ['', Validators.required];移动:字符串 = ['',Validators.required,Validators.maxLength(10)];国家:字符串 = '';}

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 = '';
}

这篇关于基于带验证模型的角度反应形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆