2
votes

When developing Angular application, to achieve 2-way binding, what is the advantage of using the [(ngModel)] approach (shown below) over the following 3 approaches (also listed below). Also, which amongst the foll. are the best options to achieve 2 way data binding (whether building forms or in general (non-form) use-case scenario)?

[(ngModel)] approach:

<input [(ngModel)]="varName">

<--OR-->

<input [ngModel]="varName" (ngModelChange)="SomeFunction($event.target.value)">

1. Input/event binding as follows:

<input [value]="aVar" (input)="aVar=$event.target.value" >
    {{aVar}}

2. Template variable as follows:

    <input [value]="bVar" (input)="bVar=ipx.value" #ipx>
{{bVar}}

3. Banana syntax approach:

 <input ([value])="cVar">
{{cVar}}
1

1 Answers

1
votes

1. NgModel

<!-- Will not work should replace with below No One -->
<input [ngModel]="varName" (ngModelChange)="SomeFunction($event.target.value)">

<!-- One -->
<input [ngModel]="varName" (ngModelChange)="varName = $event">

2. Property Binding

<input [value]="aVar" (input)="aVar=$event.target.value" >

3. #ipx call as element reference, it will give you element reference.

No 4 Banana syntax approach: will not work <input ([value])="cVar">. Because value is not a angular directive, while ngModel is a directive belongs to FormsModule.`

  • NgModel is an abstraction over all kinds of elements and components.
  • While template reference (#ipx) will only works for input elements that have a value property and emit a change event.
  • [value]="aVar" is the property binding. We are binding value property of the input element with expression name. (input)= "expression" is event binding. Whenever input event will be fired expression will be executed.

  • [(ngModel)]="varName" is the short form of [ngModel]="varName" (ngModelChange)="varName = $event"

  • Using the NgModel directive that will allows you to integrate DOM input elements and custom components into Angular form functionality.

Conclusion :

  • We can conclude that the directive ngModel is nothing but a combination of property binding and event binding.
  • Event binding is denoted using small bracket and property binding is denoted using square [] bracket, and if you notice syntax of ngModel is [(ngModel)], which is like a banana put into a box suggests it is combination of both event and property binding.

Reference Stackblitz