我正在尝试为复选框定义[[ngModel)],并使用如下形式将其转换为其他格式:
在组件文件中:
...
public roleList = [{"role":"ROLE_ADMIN","privileges":null},{"role":"ROLE_USER","privileges":null},{"role":"ROLE_READONLY","privileges":null}];
public privilegeList = [{"name":"ADMIN_READ_WRITE"},{"name":"ADMIN_READ"},{"name":"USER_READ_WRITE"},{"name":"READONLY"}];
public roleFormData = {"privileges":[{"name":null}],"role":null};
public populateRoleForm(roleForm: NgForm) {
console.log(roleForm.value);
this.roleFormData = roleForm.value;
}
...
在HTML文件中:
...
<form #roleForm="ngForm" (ngSubmit)="populateRoleForm(roleForm);" *ngIf="roleFormData">
<select name="role" [(ngModel)]="roleFormData.role">
<option *ngFor="let role of roleList" value="role.role">{{role.role}}</option>
</select>
<ng-container *ngFor="let privilege of privilegeList; let in=index">
<input type="checkbox" name="privilegeName" value="privilege.name" [(ngModel)]="roleFormData.privileges[in].name" />{{privilege.name}}
</ng-container>
<button type="submit" class="btn btn-primary">ADD</button>
</form>
...
控制台错误:
ERROR TypeError: Cannot read property 'name' of undefined
at Object.eval [as updateDirectives] (UsersComponent.html:65)
at Object.debugUpdateDirectives [as updateDirectives]
html中的第65行是:<input type="checkbox" name="privilegeName" value="privilege.name" [(ngModel)]="roleFormData.privileges[in].name" />{{privilege.name}}
在这种情况下,不确定如何为复选框定义[[ngModel)]。如何获得所需的roleFormData?
编辑:
我将HTML更改为:
<form #roleForm="ngForm" (ngSubmit)="populateRoleForm(roleForm);roleModal=false;" *ngIf="roleFormData">
<select name="roleName" [(ngModel)]="roleFormData.role">
<option *ngFor="let role of roleList">{{role.role}}</option>
</select>
<ng-container *ngFor="let privilege of privilegeList; let i=index">
<input type="checkbox" name="privilegeNames" value="{{privilege}}" [(ngModel)]="roleFormData.privileges[i].name" />{{privilege.name}}
</ng-container>
<button type="button" class="btn btn-outline" (click)="roleModal=false">CANCEL</button>
<button type="submit" class="btn btn-primary">ADD</button>
</form>
,组件为:
public roleFormData = {"privileges":[{"name":null},{"name":null},{"name":null},{"name":null}],"role":null};
但是roleForm.value
方法中populateRoleForm
的控制台给了我{roleName: "ROLE_USER", privilegeNames: true}
,但我想将privilegeNames
设为[{"name":"ADMIN_READ_WRITE"},{"name":"ADMIN_READ"}]
,即。所有选定的值。我怎么能得到这个?
答案 0 :(得分:0)
您的roleFormData.privileges
的对象数量与privilegeList
中的对象数量不同。因此,您会得到与索引1或更大的值有关的错误,roleFormData.privileges
数组中将没有对象。
要解决此问题,您可能想根据自己的目的,在privilegeList
中添加相等数量的对象,或者将[(ngModel)]="roleFormData.privileges[in].name"
更改为[(ngModel)]="roleFormData.privileges[0].name"
。
这是您推荐的Working Sample StackBlitz。