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.
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.
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.
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.
selectType
: <select (change)="selectType($event.target.value)" name="type">
ngModel
(without selectType
): <select [(ngModel)]="type" name="type">
ngModel
and ngModelChange
separately (if more processing is done in selectType
): <select [ngModel]="type" (ngModelChange)="selectType($event)" name="type">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With