lux*_*lux 81 javascript angular
我试图在检测到变化ngModel的<select>标签.在Angular 1.x中,我们可以通过$watchon ngModel或者使用来解决这个问题ngChange,但是我还没有理解如何检测ngModelAngular 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我们可以看到,如果我们从下拉列表中选择一个不同的值,我们的ngModel更改和视图中的插值表达式就会反映出来.
如何在班级/控制器中收到有关此更改的通知?
Mar*_*cok 207
更新:
分离事件和属性绑定:
<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
Run Code Online (Sandbox Code Playgroud)
onChange(newValue) {
console.log(newValue);
this.selectedItem = newValue; // don't forget to update the model here
// ... do other stuff here ...
}
Run Code Online (Sandbox Code Playgroud)
你也可以用
<select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)">
Run Code Online (Sandbox Code Playgroud)
然后你不必在事件处理程序中更新模型,但我相信这会导致触发两个事件,因此可能效率较低.
旧答案,在他们修复beta.1中的错误之前:
创建本地模板变量并附加(change)事件:
<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">
Run Code Online (Sandbox Code Playgroud)
另请参见如何在Angular 2中的"select"中获取新选择?
Log*_*n H 11
我偶然发现了这个问题,我将提交我使用过的答案并且工作得非常好.我有一个过滤的搜索框和对象数组,在我的搜索框中我使用了(ngModelChange)="onChange($event)"
在我的 .html
<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">
Run Code Online (Sandbox Code Playgroud)
然后在我的 component.ts
reSearch(newValue: string) {
//this.searchText would equal the new value
//handle my filtering with the new value
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
127829 次 |
| 最近记录: |