Hans
Hans

Reputation: 2852

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' />

Upvotes: 4

Views: 5068

Answers (3)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658087

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

Upvotes: 5

micronyks
micronyks

Reputation: 55443

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.

Upvotes: 2

Pardeep Jain
Pardeep Jain

Reputation: 86800

you can , but using [value] only like this

<input type='text' [value]='model' />

we use [(ngModel)] because it is a two way data binding, whereas [value] is one way binidng

when we use [] alongwith () it means it is two way binding.

apart from simply (input) there are no. of events are there in angular2 like mouseover mouseout etc.

Upvotes: 1

Related Questions