I am trying to build a drop down with a few values.
However, on selecting a value, I want to make an API call that takes an id.
In my component.ts, I have an array of values:
values = [
{ id: 3432, name: "Recent" },
{ id: 3442, name: "Most Popular" },
{ id: 3352, name: "Rating" }
];
In my template, I am using that array as follows:
<select>
<option *ngFor="let v of values" [value]="v">
{{v.name}}
</option>
</select>
However, on picking a value from the drop down, how can I access the id
property? I want to use that in my function getPhotosByType(id)
.
Thanks
Angular has another way to get the selected value in the dropdown using the power of ngModel and two-way data binding. The ngModel is part of the forms module. We need to import it into the NgModule list in the app. module , which will be available in our app.
Here, i will give you very simple example to getting selected option value by change event with reactive form. here we will create one website list dropdown and if you choose anyone then it will by print console selected value on change event. we created changeWebsite() that will call on change of dropdown value.
The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list.
My answer is little late but simple; but may help someone in future; I did experiment with angular versions such as 4.4.3, 5.1+, 6.x, 7.x, 8.x, 9.x, 10.x, 11.x, 12.x, 13.x, 14.x using $event (latest at the moment)
Template:
<select (change)="onChange($event)">
<option *ngFor="let v of values" [value]="v.id">{{v.name}}</option>
</select>
TS
export class MyComponent {
public onChange(event): void { // event will give you full breif of action
const newVal = event.target.value;
console.log(newVal);
}
}
You need to use an Angular form directive on the select
. You can do that with ngModel
. For example
@Component({
selector: 'my-app',
template: `
<h2>Select demo</h2>
<select [(ngModel)]="selectedCity" (ngModelChange)="onChange($event)" >
<option *ngFor="let c of cities" [ngValue]="c"> {{c.name}} </option>
</select>
`
})
class App {
cities = [{'name': 'SF'}, {'name': 'NYC'}, {'name': 'Buffalo'}];
selectedCity = this.cities[1];
onChange(city) {
alert(city.name);
}
}
The (ngModelChange)
event listener emits events when the selected value changes. This is where you can hookup your callback.
Note you will need to make sure you have imported the FormsModule
into the application.
Here is a Plunker
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