Angular 4 checkbox trigger change event on model change

耗尽温柔 提交于 2019-11-29 18:34:50

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/46647105/angular-4-checkbox-trigger-change-event-on-model-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!