Andrew Howard
Andrew Howard

Reputation: 3092

Angular 2 Reactive Forms use controls or get?

In templates I have seen both approaches:

myForm.controls.StartDate.value

and

myForm.get('StartDate').value

I thought 'controls' is now the approach going forward but when doing ng build -prod this breaks the build. What is the one to use for best practice and that won't break the build?

Upvotes: 0

Views: 463

Answers (1)

Łukasz Szcześniak
Łukasz Szcześniak

Reputation: 1444

I looked into https://angular.io/guide/reactive-forms and they use .get() on FormGroup and .controls (in template) on FormArray. Maybe that's the way, because on FormArray has non-named controls.

As stated in https://toddmotto.com/angular-2-forms-reactive, there is no difference between using .get() and .controls but that first one does error handling for you.

In my projects I use .get() on FormGroup and it works just fine. Can't tell you which approach is better nowadays. If .controls works with IDE prompts it should be the best - if it doesn't it's hard to tell the difference.

Under the hood, https://github.com/angular/angular/blob/master/packages/forms/src/model.ts#L37 .get() uses .find() and .find() uses .controls. So it should be okay to use both. Using any of them should not break your prod build.

Upvotes: 3

Related Questions