user12425844
user12425844

Reputation:

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

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

Upvotes: 0

Views: 520

Answers (1)

JB Nizet
JB Nizet

Reputation: 691755

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

Upvotes: 1

Related Questions