如何以角度响应形式将验证器添加到formModel

时间:2017-12-08 15:50:51

标签: angular angular-forms

我正在关注angular的反应式表单教程,并且想知道在使用类模型进行表单组定义时如何将属性设置为required或任何其他验证器。

https://angular.io/guide/reactive-forms#the-data-model-and-the-form-model

我注意到它创建了一个默认的空字符串作为初始值。为什么我不能在没有默认值的情况下定义地址模型 - 否则会抛出错误?例如我不能说street: string。我认为默认值在技术上满足了所需的验证 - 但这不是真实世界的用例。

理想情况下,我想定义没有默认值的类模型,并使地址和某些地址字段成为必需。这可能是使用反应形式和形式模型吗?

export class Address {
  street = '';
  city   = '';
  state  = '';
  zip    = '';
}


this.heroForm = this.fb.group({
  name: ['', Validators.required ],
  address: this.fb.group(new Address()), // <-- How to make address and certain address fields required?
  power: '',
  sidekick: ''
});

1 个答案:

答案 0 :(得分:1)

您可以提供额外的对象来添加验证器或异步验证器(请参阅文档here

Application: w3wp.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.NullReferenceException
   at System.Web.ThreadContext.AssociateWithCurrentThread(Boolean)
   at System.Web.HttpApplication.OnThreadEnterPrivate(Boolean)
   at System.Web.LegacyAspNetSynchronizationContext.CallCallbackPossiblyUnderLock(System.Threading.SendOrPostCallback, System.Object)
   at System.Web.LegacyAspNetSynchronizationContext.CallCallback(System.Threading.SendOrPostCallback, System.Object)
   at System.Threading.Tasks.AwaitTaskContinuation.RunCallback(System.Threading.ContextCallback, System.Object, System.Threading.Tasks.Task ByRef)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()

但是在这种情况下,所需要的内容将无法作为您的新地址()&#34;是一个对象,因此不是null或undefined。

您必须为您的Adress课程

创建自定义验证器
this.heroForm = this.fb.group({
  name: ['', Validators.required ],
  address: this.fb.group(new Address(), { validator: Validators.required }), // <-- How to make address required?
  power: '',
  sidekick: ''
});

希望有所帮助