如何在angular 2的ngmodel上使用二维数组? [英] How to use 2d array on ngmodel in angular 2?
问题描述
想知道如何在 ngmodel 中为动态复选框设置二维数组?
Would like to know how to set 2d array in ngmodel for dynamic checkbox?
我有一个带有多个复选框的超级管理员角色和权限设置表.如何区分模型名称与角色 ID 和权限 ID.我需要在数组中传递带有模型名称的角色 ID 和权限 ID.
I have a role and permission setup form for a super admin with multiple checkbox. How to differentiate model name with role id and permission id. I need to pass role id and permission id with the model name in an array.
例如:[(ngModel)]="permission[role.id][per.id]"
eg : [(ngModel)]="permission[role.id][per.id]"
有没有办法在 Form 中为 ngmodel 分配二维值?
Is there a way to assign 2d value for ngmodel in Form?
期待尽快回复.
提前致谢.
推荐答案
As ngModel 是获取 2-way 绑定系统的指令.
As ngModel is directive to obtain 2-way binding system.
您可以轻松地执行语法:
You can easily do the syntax:
[(ngModel)]="permission[role.id][per.id]"
其中权限是一个空数组,最初定义为:
where permission is an empty array defined initially as:
permission = []
或
permission = [[]]
您的权限变量将是一个多维数组.
where your permission variable will be a multidimensional array.
在此之后,如果您尝试使用 ngModel
After this, if you try to ngModel
[(ngModel)]="permission[role.id][per.id]"
这将导致 未定义 问题,因为 ngModel 不仅从输入中获取值,它还必须显示 2 路绑定是如何工作的.
it will cause a undefined issue as ngModel not only gets the value from input it has to show also that is how are 2-way binding works.
为了避免由于未定义而导致渲染时出现问题,我们必须最初仅将虚拟数据分配给权限数组.
To avoid issue while rendering due to undefined, we have to assign dummy data to the permission Array initially only.
this.permission = new Array(this.numberOfRoles).fill(0);
for (let j = 0; j < this.numberOfRoles; j++) {
this.permission[j] = new Array(this.numberOfPermission).fill(0);
}
这解决了如下未定义的问题
This solves the undefined issue such as below
这篇关于如何在angular 2的ngmodel上使用二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!