4
votes

I am using checkbox in angular for selecting skillSet. But when any of checkbox is checked then it checked the all checkboxes. How to solve this?

Here is my skillSet in component.ts :-

skillSet: Array<string> = ['JAVA', 'SQL', 'J2EE', 'SPRING'];

Here is checkbox field in html :-

<div class="col-md-6">
     <label for="skills">SkillSet</label><br>
     <label class="ml-2 mt-1" *ngFor ="let skill of skillSet">
     <input type="checkbox" [(ngModel)] = "employee.skills" name="skills" value="{{skill}}"> 
        {{skill}}
     </label>
</div>

Here is addEmployee.ts :-

export class Employee
{
    employeeId : number;
    firstName : string;
    lastName : string;
    age : number;
    gender : string;
    salary : number;
    department : string;
    state : string;
    city : string;
    address : string;
    email : string;
    skills : Array<{ skillName: string }>;
  }

I want to display skills json like this :-

"skills": [
            {
                "skillName": "JAVA"
            },
            {
                "skillName": "J2EE"
            }

        ]
3

3 Answers

2
votes

It is because label for and input name are the same for every input. You need to specify them. Something like name="skills-{{skill}}"

EDIT: please try this:

<div class="col-md-6">
     <label for=""skills-{{skill}}" class="ml-2 mt-1" *ngFor ="let skill of skillSet">
     <input type="checkbox" [(ngModel)] = "employee.skills" name="skills-{{skill}}" value="{{skill}}"> 
        {{skill}}
     </label>
</div>

----------------------

EDIT Nr. 2:

<div *ngFor="let skill of skills">
  <label for="{{skill.skillName}}" class="ml-2 mt-1" > {{skill.skillName}} </label>
  <input type="checkbox" id="{{skill.skillName}}" value="{{skill.skillName}}">
</div>

and:

skills = [
  {
    skillName: "JAVA"
  },
  {
    skillName: "J2EE"
  }

  ];

1
votes

You just need to do:

 [name]="skill" 
1
votes

Here:

<!-- inside an *ngFor -->
     <input type="checkbox" [(ngModel)] = "employee.skills" name="skills" value="{{skill}}"> 

every input has the same ngModel. By checking/unchecking one, you're updating the value of the one common employee.skills.

You can declare - idk, a map, an array, a plain object? - of checked skills, and bind every input to its own variable:

<input type="checkbox" [(ngModel)] = "employee.skillsDictionary[skill]"