Reputation: 9694
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}}
Upvotes: 3
Views: 978
Reputation: 2454
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">
. Becausevalue
is not a angular directive, while ngModel is a directive belongs to FormsModule.`
NgModel
is an abstraction over all kinds of elements and components. 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 :
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
Upvotes: 2