[英]How do I ensure a select change event fires AFTER ngmodel is set in Angular2?
[英]How do I detect change to ngModel on a select tag (Angular 2)?
我正在嘗試檢測<select>
標記中ngModel
的變化。 在 Angular 1.x 中,我們可能會在ngModel
上使用$watch
或使用ngChange
來解決這個問題,但我還不知道如何檢測 Angular 2 中ngModel
的變化。
完整示例: 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
會發生變化,並且視圖中的插值表達式反映了這一點。
如何在我的班級/控制器中收到此更改的通知?
更新:
分離事件和屬性綁定:
<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)">
然后您就不必在事件處理程序中更新模型,但我相信這會導致觸發兩個事件,因此效率可能較低。
舊答案,在他們修復 beta.1 中的錯誤之前:
創建一個本地模板變量並附加一個(change)
事件:
<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">
我偶然發現了這個問題,我將提交我使用過並且工作得很好的答案。 我有一個過濾對象數組的搜索框,在我的搜索框中我使用了(ngModelChange)="onChange($event)"
在我的.html
<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">
然后在我的component.ts
reSearch(newValue: string) {
//this.searchText would equal the new value
//handle my filtering with the new value
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.