66

Today I realized about an unexpected (for me) behaviour of the reactive forms in Angular 5. The server was receiving from the app an string with the value "null" instead of the null value, whichh is what I wanted.

I did the following test:

https://stackblitz.com/edit/angular-rjrspr?file=app%2Fapp.component.html

As you can see in the picture below, if I use [value]="null" in the select, the field is getting "null" (string literal) as value. However, if I use [ngValue]="null" it gets the expected null value.

enter image description here

I thought that using value was intended for reactive forms, while ngValue was for template driven forms. I'd like to know if it's safe to use both in my forms (I always use reactive forms) and if there's any explanation for the different behaviour.

Thanks!

Community
  • 1
  • 1
Fel
  • 4,428
  • 9
  • 43
  • 94
  • 2
    value always will be a string, ngValue can be an object or whatever – Eliseo Apr 19 '18 at 10:45
  • So, keeping in mind this difference, I assume that it's ok to use `value` or `ngValue` in reactive forms, isn't it? – Fel Apr 19 '18 at 11:04

5 Answers5

137

Its ok to use valueor ngValue.

The only difference between two is that value is always string, where in ngValue you can pass object

Miran Parkar
  • 1,523
  • 1
  • 10
  • 13
22

const items = ["foo", "bar", "baz"]

<option *ngFor="let item of items" [value]="item">
    {{item}}
</option>

using [value] when one of the options is selected the value will be foo, bar, baz

<option *ngFor="let item of items" [ngValue]="item">
    {{item}}
</option>

using [ngValue] when one of the options is selected the value will be 0: foo, 1: bar, 2: baz

Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
nullify0844
  • 4,641
  • 1
  • 22
  • 16
8

ngValue is valuable when you need to bind to object in the object collection instead of string that is displayed by option element as an example as follows.

  <select [(ngModel)]='selectedColor'>
    <option *ngFor="let color of colors" [ngValue]="color"  >{{color.name}}</option>
  </select>

where

  colors: [{code:'#FF0000', name:'Red'}, {code:'#00FF00', name:'Green'}, {code:'#0000FF', name:'Blue'}];

selectedColor is one of the color object above.

Ira
  • 734
  • 10
  • 7
5

there is no much diffrence between value or ngValue.

The only difference is that,

when you have String as input then use value and

when Object as input then use ngValue.

const colors= ["Red", "Green", "Blue"];

<option *ngFor="let color of colors" [value]="color">
    {{color}}
</option>
Deva
  • 1,851
  • 21
  • 22
4

value must be string but ngValue- is whatever you want. Value will not bind to selectlist if value type is int not string.

Abdus Salam Azad
  • 5,087
  • 46
  • 35