htmlangularformscheckbox

How to trigger ngModelChange with a button in Angular 2


I use *ngFor to populate my table.

<tr *ngFor= "stu in students">
<td>{{stu.name}}</td>
<td><input type="checkbox" ngModel="isChecked" 
(ngModelChange)="addID(stu.id)</td>
</tr>

Then I have a button outside the table.

<button (click)="selectAllID()">select all</button>

Then I have my component as:

studentID=[];
isChecked=false;

addID(id:number){
this.student.push (id);
//I do other thing with id
}

selectAllID (){
 If (this.isChecked)
     this isChecked = false;
  else this isChecked = true
}

The problem is:

If I check individual checkbox, the addID() function is executed. But if I click on the select all button, the checkboxes get selected. But the addID() function is not called.

How can I trigger the ngModelChange function when I use the select all button, so I get all selected ids


Solution

  • Thank you everyone. i finally resolved the issue. This is what i did:

    1. I used the selectAll() function to automatically load all id's (this id i get from the source loading my tables) to an array. and i set the value of isChecked to true or false.