Angular 2 set and bind checkboxes with a ngFor

柔情痞子 提交于 2019-12-01 00:53:02

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

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 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
    }
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!