How can I get new selection in "select" in Angular 2?
In Angular (2+), you can capture the newly selected value from a <select>
in a few ways. The most common are:
- Template-Driven Forms with
[(ngModel)]
and(ngModelChange)
, or - Reactive Forms with a
FormControl
orFormGroup
.
Below are examples using template-driven syntax—applicable in Angular 2 through the latest versions.
1. Using [(ngModel)]
Two-Way Binding
<select [(ngModel)]="selectedValue" (ngModelChange)="onSelectChange($event)"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="cherry">Cherry</option> </select>
export class MyComponent { selectedValue: string = 'apple'; onSelectChange(newVal: string) { console.log('New selection:', newVal); // do something with newVal } }
Explanation
[(ngModel)]="selectedValue"
: Binds the<select>
to theselectedValue
property, so it’s always in sync with the component.(ngModelChange)="onSelectChange($event)"
: Fires each time the user picks a new option, passing the new value toonSelectChange()
.
Requirements
- Make sure you’ve imported
FormsModule
in your@NgModule
for template-driven forms to work.
2. Using (change)
Event and [$event.target.value]
Alternatively, you can use the native (change)
event:
<select [ngModel]="selectedValue" (change)="onChange($event)"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="cherry">Cherry</option> </select>
export class MyComponent { selectedValue = 'banana'; onChange(event: Event) { const selectEl = event.target as HTMLSelectElement; const newValue = selectEl.value; console.log('Selection changed to:', newValue); } }
Explanation
(change)="onChange($event)"
captures the DOM event object.- Then you can read the new value via
event.target.value
.
3. Reactive Forms Approach (Optional Example)
If you’re using Reactive Forms:
import { FormControl } from '@angular/forms'; export class MyComponent { fruitControl = new FormControl('banana'); constructor() { this.fruitControl.valueChanges.subscribe(selected => { console.log('New selection:', selected); }); } }
<select [formControl]="fruitControl"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="cherry">Cherry</option> </select>
Explanation
[formControl]="fruitControl"
binds the<select>
to aFormControl
..valueChanges
is anObservable
that fires whenever the user picks a new option.
4. Summary
- Template-Driven: Use
[(ngModel)]
for easy two-way binding or(change)
for direct DOM events. - Reactive Forms: Use a
FormControl
(orFormGroup
) and subscribe to.valueChanges
.
Bonus: If you want to fortify your JavaScript foundations (which Angular builds upon) and sharpen your coding practices, consider the Grokking JavaScript Fundamentals course by DesignGurus.io. It covers core JS topics—like closures, prototypes, and async patterns—that translate directly to more effective Angular and TypeScript usage.
CONTRIBUTOR
TechGrind