Difference between ngValue and value in angular

Angular ngValue vs value | Angular 9, 8, 7, 6, 5, 4, 2


Difference between ngValue and value in angular - We are open to use Angular value or ngValue and the only difference between two is that the “value” is always “string”, where in “ngValue” you can pass “object”.

Let’s see the below examples in details,

Example 1,
const items = ["Anil", "Sunil", "Sushil"]

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

Result - using [value] when one of the options is selected the value will be Anil, Sunil, Sushil.

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

Result - using [ngValue] when one of the options is selected the value will be 0: Anil, 1: Sunil, 2: Sushil

Example 2,
import {Component} from '@angular/core';

@Component({
  selector: 'example-app',
  template: `
    <form #f="ngForm">
      <select name="state" ngModel>
        <option value="" disabled>Choose a state</option>
        <option *ngFor="let state of states" [ngValue]="state">
          {{ state.abbrev }}
        </option>
      </select>
    </form>
   
     <p>Form value: {{ f.value | json }}</p>
     <!-- example value: {state: {name: 'New York', abbrev: 'NY'} } -->
  `,
})
export class SelectControlComp {
  states = [
    {name: 'Arizona', abbrev: 'AZ'},
    {name: 'California', abbrev: 'CA'},
    {name: 'Colorado', abbrev: 'CO'},
    {name: 'New York', abbrev: 'NY'},
    {name: 'Pennsylvania', abbrev: 'PA'},
  ];
}

Note -
Let’s suppose there is a use case where on the dropdown you have to show the names of the objects you are populating in the dropdown. But on the other than, when selecting the single object from dropdown you have to select the id of the object for querying the database.

Well in that case, now you should go for ngValue as it expects an Object for the population of objects. Moreover your object should be initialized with the object model with which you want to populate the template.
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^