Angular 2 set and bind checkboxes with a ngFor

I have an array like this:

 objectArray = [
        {"name": "Car"},
        {"name": "Bike"},
        {"name": "Boat"},
        {"name": "Plane"}
    ];

And the template like this:

<li *ngFor="#obj of objectArray">
   <a href="#" class="small" data-value="option1" tabIndex="-1">
      <input type="checkbox" (change)="expression && expression.value = $event.target.checked ? true : undefind" [ngModel]="expression?.value">
      <label for="">{{ obj.name }}</label>
   </a>
</li>

But this is set true when 1 checkbox is checked. How do i set this separately ?

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

I guess this is what you want:

<li *ngFor="let obj of objectArray">
   <a href="#" class="small" data-value="option1" tabIndex="-1">
<input type="checkbox"  
    (change)="expression && expression[obj.name]=$event.target.checked ? true : undefined"
    [ngModel]="expression && expression[obj.name]">
   </a>
</li>

update
Using (ngModelChange) is usually better than (change) especially if [ngModel] is used

<input type="checkbox"  
    (ngModelChange)="expression && expression[obj.name]= $event ? true : undefined"
    [ngModel]="expression && expression[obj.name]">

Jason
Guest

I had some trouble figuring this out with the latest release of Angular 2. Here’s what I came up with to do two-way binding to a list of objects that contain a role name and boolean for when the role is checked. <form [formGroup]="userInfoForm" (ngSubmit)="onSubmit(userInfoForm)"> … <input type="hidden" name="roles" formControlName="roles" [(ngModel)]="roleSelections"> <div *ngFor="let role of roleSelections"> <input type="checkbox" [value]="role.isChecked" [checked]="role.isChecked" (change)="$event.target.checked ? role.isChecked = true : role.isChecked = false"> {{role.name}} </div> RoleSelection is just a simple class with two fields: export class RoleSelection { constructor( public name: string, public isChecked: boolean) { } } And in the component I had… Read more »