Mixing Reactive Form with Template Form

帅比萌擦擦* 提交于 2020-01-30 12:57:25

问题


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?


回答1:


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




回答2:


Excerpt from the link i have posted above / https://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/

Section : But what happened to ngModel?

Note that ngModel can still be used with reactive forms. It's just that the form value would be available in two different places: the view model and the FormGroup, which could potentially lead to some confusion.




回答3:


Yes,you can use both together create a reactive form first and then add template driven based on your requirement its works.Please refer angular documentation how both can be used together



来源:https://stackoverflow.com/questions/55739509/mixing-reactive-form-with-template-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!