Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 checkbox trigger change event on model change

HTML

<input type="checkbox" id="1" [(ngModel)]="filter" (change)="onFilterChange($event)"> CheckBox

<button (click)="filter = !filter">Change Status</button>

TS

export class HelloWorld {

  filter : false;

  onFilterChange() {
    console.log('filter change called');
  }
}

When I directly click on the check box change event is triggered. But when I click on "Change Status" button checkbox status is changing but change event is not triggering. Can some one please let me know how to do this?

like image 739
Pratap A.K Avatar asked Oct 09 '17 12:10

Pratap A.K


1 Answers

We have to achieve this functionality with event handler and not with 2 way binding

<input type="checkbox" id="1"
       [ngModel]="filter" (ngModelChange)="onFilterChange($event)"> Checkbox

<button (click)="onFilterChange($event)">Change Status</button>  

and in TS,

export class HelloWorld {

  filter = false;

  onFilterChange(eve: any) {
    this.filter = !this.filter;
  }
}
like image 113
Sajeetharan Avatar answered Oct 22 '22 06:10

Sajeetharan