The (change) event in Angular works differently based on how data binding is implemented. Below is a breakdown by version with examples.
In AngularJS, you use ng-model to bind the selected value and ng-change to detect changes.
HTML:
JavaScript:
$scope.devices = ['Device 1', 'Device 2', 'Device 3'];
$scope.selectedDevice = '';
$scope.onChange = function(newValue) {
console.log('New Selected Device:', newValue);
};
(ngModelChange) fires immediately when the model updates, making it ideal for real-time updates.
HTML:
TypeScript:
onChange(newValue: string) {
console.log('New Selected Device:', newValue);
}
HTML:
TypeScript:
onChange(event: Event) {
this.selectedDevice = (event.target as HTMLSelectElement).value;
console.log('New Selected Device:', this.selectedDevice);
}
Angular 17 introduced Signals, an optimized state management approach for better reactivity.
HTML:
TypeScript:
import { Component, Signal, signal } from '@angular/core';
@Component({
selector: 'app-root',
standalone: true,
templateUrl: './app.component.html',
})
export class AppComponent {
selectedDevice: Signal = signal('');
devices = ['Device 1', 'Device 2', 'Device 3'];
onChange(event: Event) {
this.selectedDevice.set((event.target as HTMLSelectElement).value);
console.log('New Selected Device:', this.selectedDevice());
}
}
Work with our skilled Angular developers to accelerate your project and boost its performance.
Hire Angular Developers