Refer to FormBuilder Members in a Strongly Type safe way, instead of strings in Angular 8

别来无恙 提交于 2020-01-16 08:40:28

问题


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.

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)]]
});

}

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();

回答1:


Sure:

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();


来源:https://stackoverflow.com/questions/59723669/refer-to-formbuilder-members-in-a-strongly-type-safe-way-instead-of-strings-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!