Angular 2: Array with checkbox not working properly


I’m binding one array with Checkbox. However, When I try to change bool attribute for single element of array but it changes for all elements.

My HTML Component is as below.

<div class="col-sm-4" *ngFor="let karyalay of karyalayListFinal">
  <div class="checkbox-fade fade-in-primary">
      <input formControlName="karyalay_group" type="checkbox" name="karyalaysCheckbox" value="{{karyalay.karyalayId}}" [(ngModel)]="karyalay.isChecked" 

Now I’m trying to change value of single or selected element as below.

for (let karyalay of this.karyalayListFinal) {
    let tempInd = _.findIndex(this.roleMasterEventList, {'KARYALAY_ID': karyalay.karyalayId});
    if (tempInd > -1) {
      this.karyalayListFinal[tempInd].isChecked = true;

Actually, if tempInd > -1 then and then only that element’s value should be changed. But it changes for all.

Don’t know whether this is ngModel issue or what?



Putting input tag inside *ngFor will create multiple input tags. And name property for input must be different for all. As HTML configure changes for input property using the name property. So, make this name property unique for every input by keeping a name field in the model passed in *ngFor.
And target the checked property instead of ngModel. And do something like
[checked]=”yourmodel.isChecked”, keep default value of isChecked property in your model as false.

Hope, it helps.

Answered By – Abhishek Kumar

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.