AnswerBun.com

Angular check and uncheck boxes from data

Stack Overflow Asked by MG91 on December 12, 2020

I have a form with multiple checkboxes. I want to check the boxes when the user has a role or a team (they can have multiple roles/teams). I also want to uncheck the boxes (remove role/team) and send the removed roles.

The data from nodejs is like this:

{
    "User": {
        "to_jsonb": {
            "roles": [
                {
                    "role_id": 1,
                    "role_name": "Admin"
                },
                {
                    "role_id": 2,
                    "role_name": "VIP"
                },
                {
                    "role_id": 1,
                    "role_name": "Moderator"
                },
                {
                    "role_id": 2,
                    "role_name": "Member"
                }
            ],
            "teams": [
                {
                    "team_id": 1,
                    "team_name": "Team 1"
                },
                {
                    "team_id": 2,
                    "team_name": "Team 2"
                },
                {
                    "team_id": 1,
                    "team_name": "Team 3"
                },
                {
                    "team_id": 2,
                    "team_name": "Team 4"
                }
            ],
            "username": "Name",
            "id": 1
            
        }
    }
}

I want to make the checkboxes (checked) if the user’s data contains any of the above (role/Team)

In HTML

   <mat-checkbox [checked]="isAdmin" name="Admin" value="1" (change)="roleChecked($event)" class="checkbox-margin-left">Admin
   </mat-checkbox>

and in profile.ts :

if (this.user.role.some(e => e.role_name === 'Admin')) {
    this.isAdmin= true;
  }

Now, this works fine, but I have about 10 teams and it doesn’t look optimal.

However, the biggest issue I am facing is when a box is unchecked. What I am currently doing is I have created an interface e.g:

export interface Roles {
    role_id: number;
    role_name: string;
}

and I am removing the roles like this:

 selectedRole : {
    role_id: number,
    role_name: string
  } [] = [];
      
roleChecked(event){
        if(event.checked){
          let roleData = {} as Roles;
          roleData.role_id = event.source.value
          roleData.role_name = event.source.name
          this.selectedRole .push(roleData);
    
          console.log(this.selectedRole );
        } else if (!event.checked){
          this.selectedRole = this.selectedRole.filter(({role_id}) => role_id !== event.source.value);
        }
      }

This adds and remove data from array of objects. However, when the page loads/initiates the array of objects is empty (obviously).

What is the optimal way to achieve this?

enter image description here

One Answer

Here is a very simple working example for your described behavior Plunker

In your component's ts-file:

  constructor() {
    // get your roles and teams from server or locally coded
    this.roles = [{id:1, name: 'Role A'}, {id:2, name: 'Role B'}, {id:3, name: 'Role C'}];
    
    // get the user to display/edit
    this.user = {
      id: 1,
      name: 'User 1',
      roles: [1,2]
    };
  }

  isUserInRole(role: IRole):boolean{
    return this.user.roles.includes(role.id);
  }

  onRoleChange(role: IRole):void{
    var index = this.user.roles.indexOf(role.id, 0);
    if (index > -1) {
      this.user.roles.splice(index, 1);
    }else{
      this.user.roles.push(role.id);
    }
    console.log(this.user.roles);
  }

In your template something like this:

 <div *ngFor='let role of roles'>
    <input type="checkbox" [checked]="isUserInRole(role)" (change)="onRoleChange(role)"/>{{role.name}}
 </div>

Correct answer by Danny Schneider on December 12, 2020

Add your own answers!

Related Questions

NGINX gives 502 error from browsers but not from Postman

1  Asked on October 13, 2020 by knguyen

   

Python Pandas cumsum with shift of n

1  Asked on October 10, 2020 by gonzalo-polo

     

How to read only half a byte from a binary file at a time in C?

2  Asked on October 9, 2020 by nguyenvivian

         

Failed to install laravel/jetstream on laravel 8

2  Asked on October 8, 2020 by vldcndn

     

liquibase roll back with spring boot

1  Asked on October 7, 2020 by user1999453

       

How to change the order of jquery events?

0  Asked on October 2, 2020 by turqay-umudzade

   

How to == async axios value

0  Asked on September 30, 2020 by jessica-bulldog

   

Is there a way to set variable methods in Python?

1  Asked on September 30, 2020 by defarm

     

How to pull data from an array using SQL

1  Asked on September 29, 2020 by sarah

     

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP