gpt4 book ai didi

javascript - Angular 4选中多个复选框

转载 作者:搜寻专家 更新时间:2023-10-30 21:49:58 25 4
gpt4 key购买 nike

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

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

从服务器加载的 Angular 色对象看起来像这样,其中包含显示在表单上的所有 Angular 色:

{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 设置多个复选框,我从服务器加载的用户对象如下所示:用户对象中的“Angular 色”是分配给用户的 Angular 色,需要在表单上检查

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

谁能帮我勾选加载的用户 Angular 色对象的复选框。提前致谢

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

enter image description here

最佳答案

您不必使用响应式表单来完成它。

HTML

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

typescript :

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

DEMO

关于javascript - Angular 4选中多个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46646576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com