Angular 4:如何将字符串数组分配给反应形式的复选框

Posted

技术标签:

【中文标题】Angular 4:如何将字符串数组分配给反应形式的复选框【英文标题】:Angular 4 : How to assign array of string into checkbox in reactive forms 【发布时间】:2017-11-30 05:37:44 【问题描述】:

我正在尝试为我的用户角色显示复选框:

例如。我有两个用户角色:1.Admin 2.Employee

我在 userObject 中有一个角色数组:

user=
    "name":"Bhushan",
    "email":"bhushan@yaho.com",
    "roles":['Admin','Employee']

我想使用响应式表单将此模型填充到表单中。我想将角色数组填充到只读复选框中,即当表单加载时,用户可以编辑姓名和电子邮件,但如果用户具有管理员角色,复选框将显示 admin 切换,如果他不是管理员,复选框将显示为未切换。员工角色也是如此。

到目前为止,我已经尝试过以下操作:

<form [formGroup]="userForm" (ngSubmit)="onSubmit()" novalidate>
  <div style="margin-bottom: 1em">
    <button type="submit" [disabled]="userForm.pristine" class="btn btn-success">Save</button> &nbsp;
    <button type="reset" (click)="revert()" [disabled]="userForm.pristine" class="btn btn-danger">Revert</button>
  </div>
  <div class="form-group">
    <label class="center-block">Name:
        <input class="form-control" formControlName="name">
    </label>
  </div>
  <div class="form-group">
    <label class="center-block">Email:
        <input class="form-control" formControlName="email">
    </label>
  </div>
  <div class="form-group" *ngFor="let role of roles;let i=index">
    <label>
        // I tried this, but it doesn't work
        <!--<input type="checkbox" [name]="role" [(ngModel)]="role">-->
       role
    </label>
  </div>
</form>

<p>userForm value:  userForm.value | json</p>`

任何输入?

【问题讨论】:

所以用户可以同时拥有AdminEmployee这两个角色?仅查看您提供的数组,两者都存在于数组中,并且没有说明该用户具有哪个角色。 你试过用patchValue 反应形式的方法吗? @AJT_82 是的。用户可以是管理员和员工 【参考方案1】:

也许做如下的事情。构建您的表单,并将角色粘贴到表单数组中:

this.userForm = this.fb.group(
  name: [this.user.name],
  roles: this.fb.array(this.user.roles || [])
);

// OPTIONAL: put the different controls in variables
this.nameCtrl = this.userForm.controls.name;
this.rolesCtrl = this.userForm.controls.roles.controls;

您在模板中迭代的角色数组可能如下所示:

roles = ['Admin', 'Employee','Some role 1', 'Some role 2']

在您的迭代中,只需比较 roles 数组中的 role 并将其设置为选中,以防它与表单数组中的值匹配。使用安全导航运算符,因为我们知道roles 数组可能比表单数组长,因此在尝试读取不存在的索引时不会抛出错误:

<div class="form-group" *ngFor="let role of roles;let i=index">
  <input [checked]="role == rolesCtrl[i]?.value" 
     [disabled]="true" type="checkbox">role
</div>

DEMO

【讨论】:

以上是关于Angular 4:如何将字符串数组分配给反应形式的复选框的主要内容,如果未能解决你的问题,请参考以下文章

将字符串数组分配给二维字符串数组

将一个字符数组分配给另一个会产生错误。为啥?

如何将 PHP 数组分配给 jQuery 数组? [复制]

如何将二维数组分配给**指针? [复制]

将文字数组分配给对象变量

C#将char和char数组分配给字符串?