检测选择标记上的ngModel更改(Angular 2)

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)

plunker

另请参见如何在Angular 2中的"select"中获取新选择?

  • @lux,是的好问题.`selectedItem`是我们绑定的数据,NgModel会自动为我们更新,但是...它没有通知我们更改,这通常是足够好的(视图等会更新),但显然这对你来说不够好用例.在我引用的另一个SO问题中,我描述了我如何尝试使用`(ngModelChange)`来获得更改通知,但每次更改都会调用它两次.我不知道这是不是一个bug.无论如何,添加一个`(change)`事件绑定似乎解决了这个问题. (2认同)

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)

  • 仅供参考,当绑定到`ngModelChange`时,`$ event`不是DOM [事件](https://developer.mozilla.org/en-US/docs/Web/API/Event).而是form元素的当前值,它是输入元素的字符串. (4认同)