2

I have worked with angular for a few years now and I have used both [value] and [ngValue] and I understand how it works - In [value]: I can only send a specific value while in [ngValue]: I can send a complete object but I It generates a bit of confusion at which moment I should use one and the other since with both of them I can get to get the data.

  • value is for string and ngValue for objects – Naga Sai A Sep 19 '19 at 15:02
  • @NagaSaiA thanks ! But when loading let's say a **select** which one is better to use? – FRANCISCO J. BLANCO Sep 19 '19 at 15:05
  • 1
    as per official anfular documentation, even for select, https://angular.io/api/forms/NgSelectOption , ngValue - Tracks the value bound to the option element. Unlike the value binding, ngValue supports binding to objects. and value - Tracks simple string values bound to the option element. For objects, use the ngValue input binding. – Naga Sai A Sep 19 '19 at 15:07

3 Answers3

3

[ngValue] when the value is and object as example select elemnt option

 const options = [{..} , {..} ,{..} ,{..}]

 <option *ngFor="let opt of options" [ngValue]="opt">{{opt.name}}</option>

[value] when the value just primitive value like number ,boolean,string

 const options = [{..} , {..} ,{..} ,{..}]

 <option *ngFor="let opt of options" [value]="opt.id">{{opt.name}}</option>
Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
  • When you use [value] and your actual value is a number or boolean it gets converted to a string. You have to convert it back again. If you're trying to deal with a nullable number and null as a possible value it gets converted to an empty string which isn't null so you need to explicitly code to convert that too. – m12lrpv May 10 '22 at 21:27
1
`const items = ["one", "two"] `

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

using [value] when one of the options is selected the value will be one, two

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

using [ngValue] when one of the options is selected the value will be 0: one, 1: two

when you have String as input then use value and

when Object as input then use ngValue.

Siddharth Pal
  • 1,408
  • 11
  • 23
0

It seems to be a duplicate of: Differences between value and ngValue in Angular 5.

  • [value] is a dynamic attribute. Each attribute of an HTML element can be dynamic (e.g.: the [href] attribute of a <a> tag, or even the [src] attribute of an <img> tag. All of this dynamic attributes only take strings

  • [ngValue] is a directive that provide extra services that value doesn't provide: in this case, passing objects that you can't pass to [value]

Maxime Lafarie
  • 2,172
  • 1
  • 22
  • 41