使用API​​中的数据填充“编辑”表单复选框-Angular [英] Fill Edit form Checkboxes with data from API - Angular

查看:84
本文介绍了使用API​​中的数据填充“编辑”表单复选框-Angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当表单处于编辑模式时,我似乎找不到合适的示例来说明如何使用API​​中的值填充复选框。

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.

我有一项服务从API获取角色数据。每个角色可以具有多个权限,例如编辑用户,创建用户,创建产品,编辑产品等。我想要一个用户可以使用复选框编辑这些角色权限的表单。我尝试过使用patchValue,如下所示,但到目前为止它什么都没有响应。

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);

        });

  }

前端:

...

<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?

推荐答案

我将稍微更改设置,并在模板中迭代一个formarray而不是 permissionList 。我还要返回ID:

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;
});

由于您的权限列表使用的是 id 作为值。

Since your permissionList is using the id as value.

因此,这就是编辑之前表单的外观。在这里,我省略了http请求,并对值进行了硬编码:

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)
}

和相关模板部分:

<label formArrayName="permissions" *ngFor="let perm of permissionsArr.controls; index as i">
  <input type="checkbox" [formControlName]="i">
  {{permissionList[i].displayName}}
</label>

因此,完成此操作后,如果要修补值,只需调用一个检查哪个ID的函数即可在 permissionList 中匹配,并在表单控件上使用 patchValue()

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)
    }
  })
}

以下是 STACKBLITZ 演示。

Here is a STACKBLITZ demo.

这篇关于使用API​​中的数据填充“编辑”表单复选框-Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆