javascriptangularangularjs-ng-change

Angular ng-change call to a Component Class function not triggering


I am trying to implement a live search box in angular using ng-change, but the function I am passing it doesn't seem to be triggering. The code is as follows

HTML

<input type="text" 
  [(ngModel)]="searchTerm" 
  ng-change="updateSearch()"
  name="firstname" 
  placeholder="Search Courses, Challenges, Datasets...">

Javascript

export class SearchbarComponent implements OnInit {

  results = RESULTS;
  filteredResults: SearchResult[];

  searchTerm: string;

  constructor() { }

  ngOnInit() {
    this.filteredResults = this.results.slice();
  }

  updateSearch():void {
    console.log("fish");
    this.filteredResults = [];

     this.results.forEach(function(element) {
       if (element.startsWith(this.searchTerm)) {
         this.filteredResults.append(element);
       }
     });

  }
updateSearch():void {
        console.log("fish");
        this.filteredResults = [];

         this.results.forEach(function(element) {
           if (element.startsWith(this.searchTerm)) {
             this.filteredResults.append(element);
           }
         });

      }
}

So I put the console log in there to see if it was triggering, not getting anything.


Solution

  • ng-change does not exist in Angular 2+ as that is Angular 1.x syntax. The syntax for Event Binding looks like (change), (input), and (click) to name a few:

    <input type="text" [(ngModel)]="someVar" (input)="someHandler($event)" />
    

    You'd need to instead use event binding (input) to track input/change events for <input /> of type text:

    <input type="text" 
        [(ngModel)]="searchTerm" 
        (input)="updateSearch()"
        name="firstname" 
        placeholder="Search Courses, Challenges, Datasets..." />
    

    You can additionally pass $event to the function in the template to gain access to the HTML Event for value, target, or anything else you may need.

    <input (input)="updateSearch($event)" />
    

    Here is a simple example of (input) event binding in action, logging the a passed $event on each input/change that occurs.

    Hopefully that helps!