Friday, 22 March 2019

Angular Form, ngModel and Detecting Changes

Angular (at the moment of writing is version 8) has two flavours when coming down to forms. We can use Template Driven or Reactive Form. Template Driven form is useful for simple form that does not need much customisation. It is similar to the form in AngularJS. Angular will create form model representation and data binding in the background with some default structure and names. That is why it is called Template Driven.

Reactive Form, on the other hand is much more flexible however requires more effort in setting up. This form uses more code in component and less in HTML. Reactive form is best to handle complex scenarios and allow easier unit testing.

We are going to see an example of Template Driven form with ngModel binding.
<form name="personNameForm" novalidate="" ng-submit="submitForm()">
 <div>
  <input type="text" name="firstName" class="textinput"
                 [(ngModel)]="person.firstName"
                 (ngModelChange)="combineNames()"
                 required />
  <input type="text" name="lastName" class="textinput"
                 [(ngModel)]="person.lastName"
                 (ngModelChange)="combineNames()"
                 required />
 </div>
</form>
Note that we need to put form's name attribute and for each ngModel field a name attribute is also required.
We use ngModelChange directive to detect changes for NgModel value. $watch and $observe are not required anymore.