如何检测选择标签(Angular 2)上对 ngModel 的更改? [英] How do I detect change to ngModel on a select tag (Angular 2)?
问题描述
我正在尝试检测 标记中
ngModel
的更改.在 Angular 1.x 中,我们可以通过 ngModel
上的 $watch
或使用 ngChange
来解决这个问题,但我还没有理解如何检测 Angular 2 中 ngModel
的变化.
I am attempting to detect a change on ngModel
in a <select>
tag. In Angular 1.x, we might solve this with a $watch
on ngModel
, or by using ngChange
, but I've yet to understand how to detect a change to ngModel
in Angular 2.
完整示例:http://plnkr.co/edit/9c9oKH1tjDDb67zdKmr9?p=info
import {Component, View, Input, } from 'angular2/core';
import {FORM_DIRECTIVES} from 'angular2/common';
@Component({
selector: 'my-dropdown'
})
@View({
directives: [FORM_DIRECTIVES],
template: `
<select [ngModel]="selection" (ngModelChange)="onChange($event, selection)" >
<option *ngFor="#option of options">{{option}}</option>
</select>
{{selection}}
`
})
export class MyDropdown {
@Input() options;
selection = 'Dog';
ngOnInit() {
console.log('These were the options passed in: ' + this.options);
}
onChange(event) {
if (this.selection === event) return;
this.selection = event;
console.log(this.selection);
}
}
如我们所见,如果我们从下拉列表中选择不同的值,我们的 ngModel
会发生变化,并且视图中的内插表达式会反映这一点.
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?
推荐答案
更新:
分离事件和属性绑定:
<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
onChange(newValue) {
console.log(newValue);
this.selectedItem = newValue; // don't forget to update the model here
// ... do other stuff here ...
}
你也可以使用
<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.
在他们修复 beta.1 中的错误之前的旧答案:
Old answer, before they fixed a bug in beta.1:
创建一个本地模板变量并附加一个(change)
事件:
Create a local template variable and attach a (change)
event:
<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">
另见 我如何获得新的选择"中的选择在 Angular 2 中?
这篇关于如何检测选择标签(Angular 2)上对 ngModel 的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!