Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngValue returning index and value

Tags:

angular

The value coming back from a select using [ngValue] is a concatenation of index and value

if I use this

<select (change)="selectType($event)" name="type" >
    <option *ngFor="let type of types" [ngValue]="type.value" >{{type.display}}</option>
</select>

and then I use this to get the value of the selected option

selectType (e) {
    this.type = e.target.options[e.target.selectedIndex].value;
}

My values look like this

0: type1
1: type2
2: type3
...

how would I just get the value? It seems ngValue is putting the index AND value in the value parameter.

like image 553
j-p Avatar asked Feb 26 '18 01:02

j-p


People also ask

What is the difference between ngValue and value?

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”. Result - using [value] when one of the options is selected the value will be Anil, Sunil, Sushil.

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.


1 Answers

Since you are handling the change DOM event, the parameter $event is the Event object supplied by the DOM, not the value of the option set with ngValue.

If you handled the ngModelChange Angular event instead, the parameter $event would be the value of the option. You could also use two-way binding with ngModel if you only need to set the value of type in the component class.

Here are the various options. You can try them in this stackblitz.

  1. Passing the value of the event target to selectType:
    <select (change)="selectType($event.target.value)" name="type">
  1. Setting the value with two-way binding using ngModel (without selectType):
    <select [(ngModel)]="type" name="type">
  1. Handling ngModel and ngModelChange separately (if more processing is done in selectType):
    <select [ngModel]="type" (ngModelChange)="selectType($event)" name="type">
like image 165
ConnorsFan Avatar answered Nov 07 '22 17:11

ConnorsFan