lux lux - 1 year ago 194
AngularJS Question

Detect change to ngModel on a select tag (Angular 2)

I am attempting to do something very simple: detect a change on

in a
tag. And in Angular 1.x, we might solve this problem with a
or by using
, but I've yet to understand how to detect a change to
in Angular 2 - mostly since the documentation is incomplete, and what blog posts and SO questions I have found were rendered obsolete weeks/months ago by the constantly evolving alpha APIs.

Here's a plunker:

As we can see, if we select a different value from the dropdown, our ngModel changes, and the interpolated expression in the view reflects this.

How do I get notified of this change in my class/controller?

Answer Source


Separate the event and property bindings:

<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
onChange(newValue) {
    this.selectedItem = newValue;  // don't forget to update the model here
    // ... do other stuff here ...

You could also use

<select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)">

and then you wouldn't have to update the model in the event handler, but I believe this causes two events to fire, so it is probably less efficient.

Old answer, before they fixed a bug in beta.1:

Create a local template variable and attach a (change) event:

<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">


See also How can I get new selection in "select" in Angular 2?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download