Search code examples
angularangular-formsangular2-ngmodel

Angular implicit ngModel change handler when ngModelChange isn't specified?


I'm experienced in the use of [(ngModel)] to achieve two-way value binding between a component field and a form control in the component's template, and the use of (ngModelChange) to perform additional work when the value has changed.

// code
foo: number;
onFooUpdate($event) { /* work */ }
// template
<input [(ngModel)]="foo" (ngModelChange)="onFooUpdate($event)" />

I'd swear that I once read that there's a name that one can use for the handler, based on the field's name, that the application will call by convention when the value changes if ngModelChanged isn't explicitly specified. Something like:

// code
foo: number;
fooChange($event) { /* work */ }
// template
<input [(ngModel)]="foo" />

where, when the value of foo changes, the application will look for a method called fooChange and, if it exists, will call it. I'm trying this now, alternatively with fooChange and fooChanged, but they aren't being called, and now I can't find any information to support this. Am I mistaken?


Solution

  • Suppose you create a property with two way data binding.

    <app-child [(test)]="qwerty"/>
    

    Then in-order for this to work, there must exist both an @Input and @Output on the child, where the criteria is that it should have the name testChange, by providing this on the child you can achieve two way data binding.

    @Input() test: string;
    @Output() testChange: EventEmitter<string> = new EventEmitter<string>();
    

    I think you misunderstood this, to think that ngModel automatically creates an output emitter with <<prop name>>Change, which is wrong.

    If you look at the source code, we only have @Output() ngModelChange, which is called when the value is changed.

    So you have to manually specify it to be called ngModelChange.