Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind directly to value property instead of ngModel

To bind the value of an input to a property, we use the ngModel directive. For example:

<input type='text' [(ngModel)]='model' />

Why can't we simply use binding on the value property of the input element?

<input type='text' [(value)]='model' />
like image 510
Hans Avatar asked Sep 12 '25 07:09

Hans


2 Answers

You can do

<input type='text' [value]='model' (input)="model=$event" />

[(value)]='model' doesn't work because the <input> doesn't emit a valueChange event.

ngModel also provides forms integration which direct value binding doesn't.

See also https://angular.io/docs/ts/latest/guide/template-syntax.html#!#two-way

ngModel uses provided ControlValueAccessors, which are directives provided for all kinds of input elements (can also be a custom one for your own components) that acts as an adapter between ngModel and any component. This is to unify binding with all kinds of components and input elements.

See also https://github.com/angular/angular/blob/2.4.8/modules/%40angular/forms/src/directives/checkbox_value_accessor.ts#L17-L50

like image 123
Günter Zöchbauer Avatar answered Sep 14 '25 22:09

Günter Zöchbauer


You can do it but...

  • Angular is famous for its inbuilt directives approach by using which you can manage/do lots of things.
  • ngModel directive allows you to use one-way or two-way binding according to your need.
  • Angular has inbuilt form-management system which is generally used with ngModel directive through which you can see whether any of form controls is valid or not and so form is valid or not.
  • ngModel directive is built with Observable and Observer pattern which allows you to emit stream of data over the time.

In short there are lots of benefits given with ngModel directive so usually people prefer to use ngModel over value syntax.

like image 21
Nikhil Shah Avatar answered Sep 14 '25 22:09

Nikhil Shah