本文介绍了以强类型安全的方式引用 FormBuilder 成员,而不是 Angular 8 中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法以强类型方式引用 Formbuilder 成员名称?如果表单生成器名称更改,则下面的 get 函数将不会注意到,也不会显示任何编译错误.这可能会导致程序功能出现问题.

Is there a way to refer to Formbuilder members names in a strongly type fashion? If form builder names change, then the get functions below will not notice, and not display any compilation error. This can create issues in program functionality.

需要以干净的方式引用 formbuilder 控件成员.

Need to refer to formbuilder control members in a clean way.

{
this.customerForm = this.formBuilder.group({
  'firstName': [null, [Validators.required,Validators.maxLength(50)]],
  'phoneNumber': [null, [Validators.required,Validators.maxLength(50)]],
  'streetName': [null, [Validators.required,Validators.maxLength(50)]],

  'emailAddress': [null, [Validators.maxLength(50), Validators.email]],
  'city': [null, [Validators.required, Validators.maxLength(200)]],
  'state': [null, [Validators.maxLength(200)]],
  'zip':[null,[Validators.maxLength(200)]]
});

}

通过字符串引用 formbuilder 成员名称,如果组件更改,则不会标记错误.

Referring to formbuilder member names through a string, which will not flag an error if component changes.

  this.customerForm.get('firstName').clearValidators();
  this.customerForm.get('firstName').updateValueAndValidity();

  this.customerForm.get('phoneNumber').clearValidators();
  this.customerForm.get('phoneNumber').updateValueAndValidity();

  this.customerForm.get('streetName').clearValidators();
  this.customerForm.get('streetName').updateValueAndValidity();

推荐答案

当然:

this.firstNameControl = 
  this.formBuilder.control(null, [Validators.required,Validators.maxLength(50)]);
this.customerForm = this.formBuilder.group({
  firstName: this.firstNameControl,
  ...
});

[...]

this.firstNameControl.clearValidators();
this.firstNameControl.updateValueAndValidity();

这篇关于以强类型安全的方式引用 FormBuilder 成员,而不是 Angular 8 中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 20:53