angularinputangular5angularjs-ng-change

What is the best ng-change/ngChange event for Angular 5 to fire a custom function?


I am trying to get the ng-change event to update a function I wrote by doing this. For now, the function only logs "I am here" to the console. I am implementing it like this:

<input type="number" ng-minlength="1" ng-maxlength="3" min="5" max="100" class="form-control" name="percentOwnership" (ng-change)="fullyOwned()"  [(ngModel)]="individualowner.percentOwnership">

I have tried to take off the one-way binding parens and also adding the two-way binding parens and brackets, but nothing fires my function to log "I am here" to the console.

I have also tried these combinations by using "change" and "ngModelChange". Still, nothing fires my function. I am using Angular 5.2.9


Solution

  • You need to use [ngModel] and (ngModelChange) separately.

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      template: `
        <input type="number" [ngModel]="percent" (ngModelChange)="onPercentChange($event)" />
      `,
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      percent = 20;
    
      onPercentChange(percent: number) {
        console.log('here');  
    
        this.percent = percent;
      }
    }
    

    Live demo

    Also your min="5" max="100" validations will not work as expected. They have been removed in Angular 4.2. Read more about the issue.