简体   繁体   中英

Multiple Checkbox value in angular2

I have one user model and one role model. I want to send value of role into db using checkbox in angular2 in http put request. I have one table user_role and I want to send role_id into that table. For the I am fetching all roles and showing it in html like this:

 <a *ngFor="let role of roles">
   <input type="checkbox" [value]="role.name" [(ngModel)]="user.role_id" [ngModelOptions]="{standalone: true}"/>&nbsp;<b>{{role.name}}</b>
 </a>

Now I want, if I will check multiple checkboxes the multiple values should go into database. I am new in angular2. Could anyone please help me in getting this?

I have created a sample demo where you can understand how multiple checkbox value can be sent to server

here is my .ts file code

roles: Array<String> = [
{
  "name":"qa",
  "isSelected": false
},
{
  "name":"developer",
  "isSelected": false
},
{
  "name":"manager",
  "isSelected": false
},
{
  "name":"BA",
  "isSelected": false
},];
sendDataToServer() {
alert(JSON.stringify(this.roles)); }

I have a json roles and a function sendDataToServer that displays the final json that is to be sent on server

here is my .html code

 <a *ngFor="let role of roles">
 <input type="checkbox" [value]="role.name" [(ngModel)]="role.isSelected"        [ngModelOptions]="{standalone: true}"/>&nbsp;<b>{{role.name}}</b>
 </a>
<br><br>
<input type="button" value="Send Data On Server "    (click)="sendDataToServer()"/>

So I have 4 checkbox and I have bind these checkbox with isSelcted property of json. As soon as user click on checkbox the value changes false to true.

when user click on sendDataToServer button then we have the updated isSelected values.

Hope this will help you. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM