Angular 4检查多个复选框

时间:2017-10-09 12:33:52

标签: javascript angular typescript checkbox

我有一个表单,用户角色显示为多个复选框:

<div *ngFor="let role of roles">
            <label for="role_{{role.id}}">
              <input type="checkbox" ngModel name="roles" id="role_{{role.id}}" value="{{role.id}}"> {{role.name}} &nbsp;&nbsp;
            </label>
          </div>

从服务器加载的角色对象如下所示,其中包含表单上显示的所有角色:

{id: 1, name: "HQ", description: "A Employee User", created_at: "2017-10-07 10:43:17",…}
1
:
{id: 2, name: "admin", description: "A Manager User", created_at: "2017-10-07 10:43:17",…}
2
:
{id: 3, name: "caretaker", description: "", created_at: null, updated_at: null}

现在我想使用form.setValue设置多个复选框,我从服务器加载的用户对象如下所示: 用户对象中的“角色”是分配给用户的角色,需要在表单

上进行检查
{
"id":13,
"name":"Wasif Khalil",
"email":"wk@wasiff.com",
"created_at":"2017-10-07 10:43:17",
"updated_at":"2017-10-09 07:45:34",
"api_token":"LKVCGPGnXZ3LyiCnyiTAg8XTpck6xWlVkeoMBgtoYZWoAOy4b5epNqMz7KG7",
"roles":[
     {"id":2,"name":"admin","description":"A Manager User","created_at":"2017-10-07 10:43:17","updated_at":"2017-10-07 10:43:17","pivot":{"user_id":"13","role_id":"2","created_at":"2017-10-07 10:43:17","updated_at":"2017-10-07 10:43:17"}
     },
     {"id":1,"name":"HQ","description":"A Employee User","created_at":"2017-10-07 10:43:17","updated_at":"2017-10-07 10:43:17","pivot":{"user_id":"13","role_id":"1","created_at":null,"updated_at":null}
     }
   ]
}

加载用户对象表单服务器即时设置值如下:

this.form.setValue({
                        name: user.name,
                        email: user.email,
                        password:"",
                        confirm_password:"",
                        roles: [1] //here im not sure how to set roles
                    });

有人可以帮我查看加载的用户角色对象的复选框。 提前致谢

编辑: 很抱歉没有解释清楚,我已经编辑了我的问题以再次解释这个问题: 用户对象上的角色是分配给用户的角色 而roles对象是要在表单中显示的所有角色的列表,请看下图:

enter image description here

1 个答案:

答案 0 :(得分:1)

您不必使用反应形式来完成它。

<强> HTML

  <input ...[checked]="check(user.roles,role.id)" ...>

<强>打字稿:

check(value1, value2){
  return (value1.filter(item => item.id == value2)).length
}

DEMO