Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between value and ngValue in Angular 5

People also ask

What is the difference between value and value in angular?

And the difference between value= and [value]= is the first one is for string binding (when you already know the value) and the 2nd one is for variable binding. It worked. Thanks!

What is use of ngValue in angular?

The ng-value directive sets the value attribute of a input element, or a select element.

What is the use of ngValue?

It is mainly used on input[radio] and option elements, so that when the element is selected, the ngModel of that element (or its select parent element) is set to the bound value. It is especially useful for dynamically generated lists using ngRepeat , as shown below.


Its ok to use valueor ngValue.

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


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


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.


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>

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