使用来自 API 的数据填充编辑表单复选框 - Angular [英] Fill Edit form Checkboxes with data from API - Angular
问题描述
当表单处于编辑模式时,我似乎找不到如何用 API 中的值填充复选框的正确示例.
我有一个从 API 获取角色数据的服务.每个角色都可以有多个权限,如编辑用户、创建用户、创建产品、编辑产品等.我想要一个表单,用户可以在其中使用复选框编辑这些角色权限.我尝试使用 patchValue 如下所示,但到目前为止它没有任何响应.
rolePermissionList = [];权限列表 = [];设置表格(){this.roleForm = this.fb.group({role_name: ["", Validators.required],描述: [""],地位: [""],权限:this.fb.array([]),}, {updateOn: '改变'});}ngOnInit() {this.setupForm();this.route.paramMap.subscribe(params => {this.id = parseInt(params.get("id"));//获取单个角色记录this.getPageData(this.id);})}//获取页面数据异步 getPageData(role_id) {this.spinner.show();//获取角色等待 this.getRole(role_id);//获取所有权限等待 this.getPermissions();//获取角色权限等待 this.getRolePermissions(role_id);this.spinner.hide();}
我有两个服务:一个返回整个权限列表,另一个返回分配给当前角色的权限.我想要一种仅检查分配给正在编辑的当前角色的权限的方法.这些是获取所有权限和角色权限的函数:
//获取权限列表获取权限(){this.permissionService.getPermissionsList().订阅(数据 =>{console.log("权限 === ", 数据);this.permissionList = 数据;},错误 =>控制台日志(错误));}//获取角色权限getRolePermissions(role_id?:any) {//如果提供了 role_id让参数 = 新的 HttpParams();如果(role_id){params=params.set('role_id', role_id.toString());}this.rolePermissionService.getRolePermissionsList(params).订阅(数据 =>{//存储获取的数据this.rolePermissionList = 数据;//从返回的数组中提取权限名称var arrayOfPerms = data.map(function(obj) {返回对象名称;});//补丁数据this.roleForm.pastchValue('permissions', arrayOfPerms);},错误 =>{控制台日志(错误);});}
前端:
<代码>...<div class="row" *ngIf="permissionList; else loading"><div *ngFor="let permissionList; let i=index" class="col-md-6"><div class="custom-control custom-checkbox mr-sm-2 m-b-15"><输入类型=复选框"[值]="权限.id"(change)="onCheckChange($event)"类=自定义控制输入"id="checkbox-{{ i }}"><label class="custom-control-label" for="checkbox-{{ i }}">{{permission.display_name }}</label>
...
任何帮助将不胜感激?
我会稍微改变设置,并在模板中迭代一个表单数组而不是 permissionList
.我也会返回 id:
var arrayOfPerms = data.map(function(obj) {返回 obj.id;});
因为您的 permissionList
使用 id
作为值.
这就是表单在编辑前的样子.这里我省略了 http 请求并对值进行了硬编码:
permissionList = [{ id: 1, displayName: 'Admin' },{ id: 2, displayName: '用户' },{ id: 3, displayName: '超级用户' }];rolePermissionList = [1, 3];构造函数(私人FB:FormBuilder){//最初将所有复选框设置为 falseconst ctrls = this.permissionList.map(control => this.fb.control(false));this.roleForm = this.fb.group({权限:this.fb.array(ctrls),});}//为了能够缩短获取权限Arr(){返回 this.roleForm.get('permissions') 作为 FormArray;}提交() {//过滤选中的并存储在数组中const selectedRoles= this.roleForm.value.permissions.map((checked, i) => checked ? this.permissionList[i].id : null).filter(value => value !== null);//这是一个 id 数组,例如 [1, 3]console.log(selectedRoles)}
以及相关的模板部分:
因此,当完成后,您想要修补值,只需调用一个函数来检查 permissionList
中的哪个 id 匹配,然后使用 patchValue()
表单控件:
patchValue() {this.permissionList.map((perm, i) => {如果 (this.rolePermissionList.indexOf(perm.id) !== -1) {this.permissionsArr.at(i).patchValue(true)}})}
这是一个 STACKBLITZ 演示.
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 = [];
permissionList = [];
setupForm() {
this.roleForm = this.fb.group({
role_name: ["", Validators.required],
description: [""],
status: [""],
permissions: this.fb.array([]),
}, {updateOn: 'change'});
}
ngOnInit() {
this.setupForm();
this.route.paramMap.subscribe(params => {
this.id = parseInt(params.get("id"));
// fetch single role record
this.getPageData(this.id);
})
}
// get page data
async getPageData(role_id) {
this.spinner.show();
// get role
await this.getRole(role_id);
// get all permissions
await this.getPermissions();
// get role permissions
await this.getRolePermissions(role_id);
this.spinner.hide();
}
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-{{ i }}">
<label class="custom-control-label" for="checkbox-{{ i }}">{{ permission.display_name }}</label>
</div>
</div>
</div>
...
Any help will be greatly appreciated?
I would change the setup a bit, and iterate a formarray in the template instead of permissionList
. Also I would return the id:
var arrayOfPerms = data.map(function(obj) {
return obj.id;
});
Since your permissionList
is using the id
as value.
So this is how the form would look before edit. Here I have omitted the http-request and hard coded the values:
permissionList = [
{ id: 1, displayName: 'Admin' },
{ id: 2, displayName: 'User' },
{ id: 3, displayName: 'SuperUser' }
];
rolePermissionList = [1, 3];
constructor(private fb: FormBuilder) {
// set all checkboxes as false initially
const ctrls = this.permissionList.map(control => this.fb.control(false));
this.roleForm = this.fb.group({
permissions: this.fb.array(ctrls),
});
}
// for being able to shorten
get permissionsArr() {
return this.roleForm.get('permissions') as FormArray;
}
submit() {
// filter the checked and store in array
const selectedRoles= this.roleForm.value.permissions
.map((checked, i) => checked ? this.permissionList[i].id : null)
.filter(value => value !== null);
// here is an array of ids, e.g [1, 3]
console.log(selectedRoles)
}
and the relevant template part:
<label formArrayName="permissions" *ngFor="let perm of permissionsArr.controls; index as i">
<input type="checkbox" [formControlName]="i">
{{permissionList[i].displayName}}
</label>
So when that is done, and you want to patch values, just call a function that checks which id's that match in permissionList
, and use patchValue()
on the form control:
patchValue() {
this.permissionList.map((perm, i) => {
if (this.rolePermissionList.indexOf(perm.id) !== -1) {
this.permissionsArr.at(i).patchValue(true)
}
})
}
Here is a STACKBLITZ demo.
这篇关于使用来自 API 的数据填充编辑表单复选框 - Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!