3

Would like to know how to set 2d array in ngmodel for dynamic checkbox?

I have a role and permission setup form for a super admin with multiple checkbox. enter image description here 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.

eg : [(ngModel)]="permission[role.id][per.id]"

Is there a way to assign 2d value for ngmodel in Form?

Looking forward for an earliest response.

Thanks in advance.

2
  • Have you already tried it? Commented Jan 11, 2017 at 8:12
  • yes, but its not working. Commented Jan 11, 2017 at 9:05

1 Answer 1

2

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 = []

or

permission = [[]]

where your permission variable will be a multidimensional array.

After this, if you try to ngModel

[(ngModel)]="permission[role.id][per.id]"

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

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.