I'm currently learning angular& I was reading about differences between reactive forms and template-driven forms from https://angular.io/guide/forms-overview. The website says reactive forms are immutable and template-driven forms are mutable. I don't really understand what immutable in this context means.I mean if user can update the state of the form by providing values to form controls, doesn't that make form mutable?
1 Answers
There are loads of articles about Angular forms. Most of them simply rephrase the documentation and slightly modify the examples, without actually explaining what is meant. I had to go through Angular documentation several times to try to understand what they mean. I assume you're familiar with the mutability concept.
What they say is mutable/immutable is the underlying data model, not the forms themselves. Even that is not 100% clear to me, as sometimes they talk about form model instead. But the key difference is that with Reactive forms you do not have a materialized model object. Instead, you have a set of FormControls, with which you interact directly via the API. In this context, immutable does not mean you cannot change the properties/values. It means that after the state of the underlying model changes, you're working with a new 'instance' of that model, that has been synchonously updated with the new values and keeps aligned with the (UI) controls at any point in time. The source of truth is therefore the form model. It's worth digging deeper into Observables to understand how that is achieved.
With Template-driven forms, you do not access or modify the FormControls. You have view model objects and/or properties in the controller, that are linked to the UI through the NgModel directive. Those objects/properties may change, that is why they talk about mutability for this type of form. The change detection is asynchronous, so it could happen, even if not likely, that at some point of time, the template (UI), the form model and the view (data) model are not aligned.
From this article: "The second issue is that the two-way bound data is mutable, which essentially means that you cannot guarantee that the data isn’t going to be changed whilst you are working with it. We will never be sure if what we can see is accurate or if it will be changed whilst we are working with the data due to the asynchronous nature of the two-way binding."
Hope this helps!