0

ngModel如果输入字段的值已更改,我想在 Angular2 组件中运行一些代码。我想收听该(input)事件,因为它是在任何类型的用户交互时触发的。这意味着我无法使用(change)这里使用该事件。我只想在值发生变化时运行我的代码。

这是一个示例组件:

import { Component } from '@angular/core';

@Component({
    selector: 'myCuteComponent',
    templateUrl: `
        <h1>yoO World</h1>
        <input [(ngModel)]="cuteValue" (input)="onInput($event)">
    `
})
export class MyCuteComponent {

    cuteValue = '';

    constructor() { }

    onInput(event) {
        if (event.target.value !== this.cuteValue) {
            console.log('value has changed'); // this will never run :(
        }
    }
}

问题是它在被触发event.target.value时已经包含了新值。onInput所以这种方式行不通,console.log will永远不会运行。

问题:是否有适当的(和通用的)解决方案来检测在任何类型的用户交互后价值是否真的发生了变化?

4

2 回答 2

3

尝试这个:

import { Component} from '@angular/core';

@Component({
    selector: 'myCuteComponent',
    templateUrl: `
        <h1>yoO World</h1>
        <input [(ngModel)]="cuteValue" (ngModelChange)="onInput($event)">
    ` }) export class MyCuteComponent {

    onInput(value) {
        console.log(value);
    }
}

ControlValueAccessors 将用方括号写入初始值,并用香蕉括号发出值变化。因此 [ngModel] 和 (ngModelChange) 被缩短为 [(ngModel)] 以绑定和发出更改。

于 2016-12-08T03:01:33.533 回答
1

您是否尝试过使用 OnChanges ( https://angular.io/docs/ts/latest/api/core/index/OnChanges-class.html )?

就像是:

import { Component, OnChanges } from '@angular/core';

@Component({
    selector: 'myCuteComponent',
    templateUrl: `
        <h1>yoO World</h1>
        <input [(ngModel)]="cuteValue" (input)="onInput($event)">
    `
})
export class MyCuteComponent implements OnChanges {

    ngOnChanges(changes: SimpleChanges) {
        // changes.prop contains the old and the new value...
    }
}
于 2016-12-08T02:26:24.323 回答