Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing Reactive Form with Template Form

I have built a big form with lots of input using Template Form. Now I have got a requirement to add a part of input dynamically. Since adding inputs dynamically seems easier with Reactive Form, I would like to change that specific part of inputs to Reactive Form.

So is it possible to mix reactive forms and template forms in a same form tag?

like image 425
suhailvs Avatar asked Apr 18 '19 05:04

suhailvs


People also ask

Should I use template driven forms or Reactive forms?

Template Driven Forms are based only on template directives, while Reactive forms are defined programmatically at the level of the component class. Reactive Forms are a better default choice for new applications, as they are more powerful and easier to use.

Can we use ngModel with Reactive forms?

You can use [(ngModel)] with Reactive forms. This will a completely different directive than the one that would be used without the formControlName . With reactive forms, it will be the FormControlNameDirective . Without the formControlName , the NgModel directive would be used.

Can we use ngModel and formControlName together?

It looks like you're using ngModel on the same form field as formControlName. Support for using the ngModel input property and ngModelChange event with reactive form directives has been deprecated in Angular v6 and will be removed in Angular v7.

What is the difference between template and Reactive forms in Angular?

Template-driven forms are asynchronous in nature, whereas Reactive forms are mostly synchronous. In a template-driven approach, most of the logic is driven from the template, whereas in reactive-driven approach, the logic resides mainly in the component or typescript code.


Video Answer


1 Answers

You can mix both reactive forms and template driven forms, but it is highly not recommended. This is because using ngModel on reactive forms goes against the idea of immutability of the form state.

The principles of reactive forms follows the 'one-way' data binding rule, whereby you follow an immutable method of managing the state of your forms, such that there is greater separation of concern between your template and component logic. You can read more about the advantages of reactive forms on the link at the first paragraph.

Assuming you are going ahead with mixing template driven forms and reactive forms. The console will throw the following error when you run ng serve:

It looks like you're using ngModel on the same form field as formControlName. Support for using the ngModel input property and ngModelChange event with reactive form directives has been deprecated in Angular v6 and will be removed in Angular v7 For more information on this, see our API docs here: https://angular.io/api/forms/FormControlName#use-with-ngmodel

like image 185
wentjun Avatar answered Sep 27 '22 23:09

wentjun