I am pretty new to angular and learning formArray. I have 2 simple lists of roles and rights. For this, I need to plot a checkbox matrix as follows. Also, at the bottom of every column, I need to show the total count of selected rights.
following is the component.ts code that I have written to achieve the above logic.
constructor(private fb: FormBuilder) {
}
roleRightsForm: FormGroup;
roles = [
{ id: 1, name: 'Admin' },
{ id: 2, name: 'User' },
// Add more roles here
];
rights = [
{ id: 1, name: 'Create' },
{ id: 2, name: 'Read' },
{ id: 3, name: 'Update' },
{ id: 4, name: 'Delete' },
];
initRoles(): void {
this.roleRightsForm = this.fb.group({
roles: this.fb.array([]),
});
const rolesFormArray = this.roleRightsForm.get('roles') as FormArray;
this.roles.forEach(role => {
const roleFormGroup = this.fb.group({
role: [role],
rights: this.fb.array([])
});
this.rights.forEach(right=>{
const rightFormArray = roleFormGroup.get('rights') as FormArray;
rightFormArray.push( new FormControl(false));
})
rolesFormArray.push(roleFormGroup);
});
}
get getRoles(){
return (this.roleRightsForm.get('roles') as FormArray).controls;
}
and following is the html code.
<form [formGroup]="roleRightsForm">
<table>
<thead>
<tr>
<th></th>
<th *ngFor="let right of rights">{{ right.name }}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let roleGroup of getRoles; let i = index" [formGroup]="roleGroup" >
<td>{{ roleGroup.value.role.name }}</td>
<td *ngFor="let right of rights; let j = index" >
<input type="checkbox" [formControlName]="i + '-' + right.id">
</td>
</tr>
</tbody>
</table>
</form>
But getting the following error.
main.ts:6 ERROR Error: Cannot find control with name: '0-1'
at _throwError (forms.mjs:3150:11)
at setUpControl (forms.mjs:2933:13)
at FormGroupDirective.addControl (forms.mjs:4782:9)
at FormControlName._setUpControl (forms.mjs:5370:43)
at FormControlName.ngOnChanges (forms.mjs:5315:18)
at FormControlName.rememberChangeHistoryAndInvokeOnChangesHook (core.mjs:2948:14)
at callHookInternal (core.mjs:3940:14)
at callHook (core.mjs:3971:9)
at callHooks (core.mjs:3922:17)
at executeInitAndCheckHooks (core.mjs:3872:9)
Need guidance on what I am doing wrong here. Also, to show the count under every column of selected rights, should I add a property "count" in "roleFormGroup" and on the checkbox change event, increase/decrease the count in the property? or is there a better way?
Sorry, if the questions are too basic. I am from a jQuery background and trying to wrap my head around Angulalr.