定义[(ngModel)]复选框数组以使用表单获取不同JSON格式的输出

时间:2018-12-11 07:05:33

标签: angular typescript angular-forms

我正在尝试为复选框定义[[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>&nbsp;&nbsp;
    <ng-container *ngFor="let privilege of privilegeList; let i=index">
        <input type="checkbox" name="privilegeNames" value="{{privilege}}" [(ngModel)]="roleFormData.privileges[i].name" />{{privilege.name}}&nbsp;&nbsp;
    </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"}],即。所有选定的值。我怎么能得到这个?

1 个答案:

答案 0 :(得分:0)

您的roleFormData.privileges的对象数量与privilegeList中的对象数量不同。因此,您会得到与索引1或更大的值有关的错误,roleFormData.privileges数组中将没有对象。

要解决此问题,您可能想根据自己的目的,在privilegeList中添加相等数量的对象,或者将[(ngModel)]="roleFormData.privileges[in].name"更改为[(ngModel)]="roleFormData.privileges[0].name"


这是您推荐的Working Sample StackBlitz