I am working on a form in Angular that includes checkboxes. I want to automatically check the checkbox if the user has a specific role.
Here is my current approach:
<form [formGroup]="rolesForm">
<label
formArrayName="roles"
*ngFor="let role of rolesForm.controls['roles'].controls; let i = index"
>
<input
type="checkbox"
[checked]="checkIfTrue(role[i])"
[formControlName]="i"
/> {{role[i].name}}
</label>
</form>
This is part of the component:
roles: Role[] = [
{
uid: '456DNC',
name: 'Admin'
},
{
uid: '546DKZ',
name: 'Member'
},
{
uid: '741JXY',
name: 'Guest'
}
]
user: User = {
uid: '123ABC',
name: 'Steve',
roles: [
{
uid: '456DNC',
name: 'Admin'
}
]
}
rolesForm: FormGroup;
ngOnChanges() {
const formControls = this.roles.map(role => new FormControl(false));
this.rolesForm = this.formBuilder.group({
roles: new FormArray(formControls)
});
}
checkIfTrue(role: Role) {
return this.user.roles.find(role);
}
An error message I'm encountering is:
[object Object] is not a function at Array.find
In trying to resolve the issue, I experimented with using .indexOf() and .includes()