Issue
i want to get the value and label of my select option and mapp the to my reactive Form. this is my html:
<select class="form-control" (change)="onChange($event.target)">
<option value=""></option>
<option value="C1">Country 1</option>
<option value="C2">Country 2</option>
<option value="C3">Country 3</option>
</select>
and this is my ts code :
onChange(event: any) {
// here i want to get the value and label of my selected item (C2 , Country 2 for example)
console.log(event.value); // this print only the value C1,2,3
}
Solution
Updated Answer
HTML:
<select (change)="onChange($event)" formControlName="country"></select>
TS:
onChange($event: any) {
let text = $event.target.options[$event.target.options.selectedIndex].text;
this.yourForm.patchValue({ labelText: text });
console.log(text);
}
The (change) should get the text that represents the option, and the formControlName should retrieve the value from the option.
patchValue will change the form value for the value that you want, you just need to type the name of the formControl: labelText and after the : the desired value!
About the value from the option, if you have a formControlName on the select, it will automatically change the formControl value!
Answered By - hikitan1
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.