I cant seem to find a proper example of how to fill a checkbox with values from an API when a form is in edit mode.
I have a service that fetches roles data from an API. Each role can have multiple permissions like edit-user, create-user, create-product, edit-product, etc. I want a form where a user can edit these role permissions using checkboxes. I have tried using patchValue as shown below but it doesnt respond to anything so far.
rolePermissionList = [];
setupForm() {
this.roleForm = this.fb.group({
role_name: ["", Validators.required],
description: [""],
status: [""],
permissions: this.fb.array([]),
}, {updateOn: 'change'});
}
I have two services: one that returns the entire permissions list, and the other that returns permissions assigned to the current role. I want a way to check only permissions assigned to the current role being edited. These are the functions that fetch all permissions and rolepermissions:
// get permissions list
getPermissions() {
this.permissionService.getPermissionsList()
.subscribe(
data => {
console.log("permissions === ", data);
this.permissionList = data;
},
error => console.log(error));
}
// get role permissions
getRolePermissions(role_id?:any) {
// if role_id is supplied
let params = new HttpParams();
if (role_id) {
params=params.set('role_id', role_id.toString());
}
this.rolePermissionService.getRolePermissionsList(params)
.subscribe(
data => {
// store fetched data
this.rolePermissionList = data;
// extract permission name from returned array
var arrayOfPerms = data.map(function(obj) {
return obj.name;
});
// patch data
this.roleForm.pastchValue('permissions', arrayOfPerms);
},
error => {
console.log(error);
});
}
The front end:
...
<div class="row" *ngIf="permissionList; else loading">
<div *ngFor="let permission of permissionList; let i=index" class="col-md-6">
<div class="custom-control custom-checkbox mr-sm-2 m-b-15">
<input type="checkbox"
[value]="permission.id"
(change)="onCheckChange($event)"
class="custom-control-input"
id="checkbox-">
<label class="custom-control-label" for="checkbox-"></label>
</div>
</div>
</div>
...
Any help will be greatly appreciated?
Aucun commentaire:
Enregistrer un commentaire