我在使用最新版本的 Angular 2 时遇到了一些麻烦。这是我想出的对包含角色名称和布尔值的对象列表进行双向绑定的方法,用于检查角色。
<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 只是一个具有两个字段的简单类:
export class RoleSelection {
constructor(
public name: string,
public isChecked: boolean)
{ }
}
在组件中,我必须在创建 FormGroup 时声明一个名为 roles 的属性,然后将其绑定到上面 HTML 中的隐藏字段。
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)
});
然后在提交表单后,ngSubmit 方法只需提取它需要的内容:
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
}
}