mardi 6 juin 2017

two-way binding on checkbox ngFor Angular2

I am creating an Angular2 project and having a problem with two-way binding for a checkbox.

I have a class called listItem and List like that:

export class ListItem {
  public count: number;
  public value: string;
  public checked: boolean;

  constructor(count: number, value: string, checked: boolean) {
    this.count = count;
    this.value = value;
    this.checked = checked;
  }
}

export class MyList{
  public category: string;
  public listItem : ListItem [];

  constructor(category: string, listItem : ListItem []) {
    this.category = category;
    this.listItem = listItem ;
  }
}

and I am calling the list from Azure search which is working correctly. the problem is when I just set the value to a checkbox.

<div *ngFor="let list of myList; let listIndex = index;">
  <div *ngFor="let item of list.listItems; let itemIndex = index;">
    <input type="checkbox" [name]="list.category + item.value"
         (change)="item.checked = !item.checked"
         [ngModel]="item.checked" />
  </div
</div>

but the value is always false also onClick. I tried to use [(ngModel)] but did not work also. I also tried to make a function:

(change)="oncheck(listIndex, itemIndex)"

oncheck(listIndex: number, itemIndex: number) {
   this.myList[listIndex].listItems[itemIndex].checked =  
           !this.myList[listIndex].listItems[itemIndex].checked;
  } 

but I received this error:

Cannot assign to read-only property 'checked' of object '[object Object]'

why is that and how to fix it? thank you




Aucun commentaire:

Enregistrer un commentaire