Angular 2 set and bind checkboxes with a ngFor

Issue

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 ?

Solution

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]">

Answered By – Günter Zöchbauer

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.