Samuel
Samuel

Reputation: 1416

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

Is there any preferred way when selecting validation using

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.

Upvotes: 67

Views: 91418

Answers (4)

xianshenglu
xianshenglu

Reputation: 5359

In Angular@17 myForm.controls['name'] reflects the real type which can avoid some type issues.

let nameCtrl = myForm.controls['name'] // FormControl<type>
let nameAbstractCtrl = myForm.get('name') // AbstractControl
nameCtrl = nameAbstractCtrl // Type 'AbstractControl' is missing the following properties from type 'FormControl': defaultValue, registerOnChange, registerOnDisabledChangets(2739)

Upvotes: 1

oleg gabureac
oleg gabureac

Reputation: 853

IMHO if you are using typed forms is better using

myForm.controls.controlName

In this case if you have a control that is of type FormGroup or FormArray you don't need to cast it to a type

((this.form.get('arrayControl') as FormArray).at(index) as FormGroup).contains(controlName)

you can write just this

this.form.controls.arrayControl.at(index).contains(controlName)

Upvotes: 0

This question is related to: Will using Angular Reactive Forms .get() method in template cause unnecessary method calls like a component method?.

In templates I prefer using myForm.controls.name to avoid the myForm.get('name') function call. If the field selector is very complex, then I would store the field in a component attribute so in the template its access is instant.

In controllers it shouldn't matter too much using one or another.

Upvotes: 10

Pengyy
Pengyy

Reputation: 38191

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

Upvotes: 61

Related Questions