Angular 2 set and bind checkboxes with a ngFor

Sireini picture Sireini · Apr 11, 2016 · Viewed 26k times · Source

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 ?

Answer

David Spenard picture David Spenard · Dec 23, 2016

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.

enter image description here

<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 to declare a property called roles when creating a FormGroup, and then bind this to the hidden field in the HTML above.

    this.userInfoForm = new FormGroup({
        emailAddress: new FormControl(this.userInfo.emailAddress, Validators.required),
        firstName: new FormControl(this.userInfo.firstName, Validators.required),
        middleName: new FormControl(this.userInfo.middleName),
        lastName: new FormControl(this.userInfo.lastName, Validators.required),
        isAdmin: new FormControl(this.userInfo.isAdmin),
        isArchived: new FormControl(this.userInfo.isArchived),
        roles: new FormControl(this.roleSelections)
    });

Then upon submission of the form, the ngSubmit method just has to pull out what it needs:

 private onSubmit(obj: any) {
    if (obj.valid) {
        let account: IUserAccount = {};
        account.id = this.userAccountId;
        account.firstName = obj.controls.firstName.value;
        ...
        ...
        // get list of roles checked via obj.controls.roles.value[i].isChecked etc
        ...
        ...
        // do submission
    }
 }