Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formGroup.get vs formGroup.controls in reactive form - Angular

Is there any preferred way when selecting validation using

  • myForm.controls['name'].valid
  • myForm.get('name').valid

as both seems to be only syntactically different but achieving the same goal.

<label>Name   <input type="text" formControlName="name"> </label> <div class="alert" *ngIf="!myForm.controls['name'].valid && myForm.controls['name'].touched">   {{ titleAlert }} </div> 

Same as

<div class="alert" *ngIf="!myForm.get('name').valid && myForm.get('name').touched">   {{ titleAlert }} </div> 

From what I checked in the code, get has this code:

AbstractControl.prototype.get = function (path) { return _find(this, path, '.'); }; 

I have just started Angular, so an expert opinion would be appreciated.

like image 934
Samuel Avatar asked Apr 04 '18 04:04

Samuel


People also ask

What is difference between FormBuilder and FormControl?

In Angular, a reactive form is a FormGroup that is made up of FormControls. The FormBuilder is the class that is used to create both FormGroups and FormControls.

What is the difference between formControlName and FormControl?

[formControl] assigns a reference to the FormControl instance you created to the FormControlDirective . formControlName assigns a string for the forms module to look up the control by name.

What is the difference between FormGroup and FormControl?

FormControl and FormGroup in AngularFormGroup is used with FormControl to track the value and validate the state of form control. In practice, FormGroup aggregates the values of each child FormControl into a single object, using each control name as the key.


1 Answers

Just like what you have found, FormGroup.get is designed to access target formcontrol by it's path. And it's more often used for complicated(multi layer embed) situation, which makes it easy to get the target control from multi layer embed form and also makes code clear and easily to understand.

Take below as a example, you can simply access the first element of the embed FormArray by this.form.get('test.0') instead of this.form.controls.test.controls[0]:

this.form = this.formBuilder.group(   {     test: this.formBuilder.array(       [         ['form control 1 in form array'],         ['form control 1 in form array'],         ...       ]     )   } ); 
like image 131
Pengyy Avatar answered Sep 22 '22 19:09

Pengyy