Burnee
Burnee

Reputation: 2623

How to check in the Angular2 (input) handler if the value is really changed

I want to run some code in an Angular2 component if the ngModel of an input field has changed. I want to listen on the (input) event because it's fired on any type of user interaction. This means that I can't use the (change) event here. I want to run my code only if the value has changed.

Here is an example component:

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 :(
        }
    }
}

The problem is that event.target.value contains the new value already when onInput is fired. So this way won't work, the console.log will never run.

Question: Is there a proper (and general) solution to detect if value has really changed after any type of user interaction?

Upvotes: 0

Views: 1411

Answers (2)

Yodacheese
Yodacheese

Reputation: 5037

Try this:

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 will write the initial value with square brackets, and emit values changes with banana brackets. So [ngModel] and (ngModelChange) is shortened to [(ngModel)] to bind and emit on changes.

Upvotes: 3

Michael McGowan
Michael McGowan

Reputation: 566

Have you tried using OnChanges (https://angular.io/docs/ts/latest/api/core/index/OnChanges-class.html)?

Something like:

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...
    }
}

Upvotes: 1

Related Questions