Angular 4 getting values from checkboxes

22,977

Solution 1

You can add a change event to md-checkbox and pass the object to a function. Maintain an array that keep track of which ones got checked and unchecked and update the array according to that.

html:

<span *ngFor="let x of maintainanceTypeList">
    <md-checkbox 
       name="{{x.maintenancetype}}" 
       value="{{x.maintenancetype}}"
       (change)="change($event, x)">
         {{x.maintenancetype}}
    </md-checkbox>
</span>

<p> Selected value: {{selectedValue | json}} </p>

component.ts:

export class SelectFormExample {
  selectedValue = [];

  maintainanceTypeList = [
    {maintenancetype: 'Steak'},
    {maintenancetype: 'Pizza'},
    {maintenancetype: 'Tacos'}
  ];

  change(e, type){
    console.log(e.checked);
    console.log(type);
    if(e.checked){
      this.selectedValue.push(type);
    }
    else{
     let updateItem = this.selectedValue.find(this.findIndexToUpdate, type.maintenancetype));

     let index = this.selectedValue.indexOf(updateItem);

     this.selectedValue.splice(index, 1);
    }

  }

  findIndexToUpdate(type) { 
        return type.maintenancetype === this;
    }
}

Plunker demo

Solution 2

Instead of e.checked you can use the following:

Working example

HTML

<input class="form-check-input" type="checkbox" (change)="selectBadge($event, badge._id)">

Typescript

selectBadge (e, id) {

 if (e.target.checked) {
   this.product.badges.push(id);
 }  else {
   this.product.badges.splice(this.product.badges.indexOf(id), 1);
 }

}
Share:
22,977
Ninad Gaikwad
Author by

Ninad Gaikwad

Updated on November 10, 2020

Comments

  • Ninad Gaikwad
    Ninad Gaikwad over 3 years

    I am new to angular and am stuck at this pretty simple problem. I am getting data from a webservice to show a couple of checkboxes. I need a way to get the value of all of the checkboxes selected by the user. I am using material theme.

    <span *ngFor="let x of maintainanceTypeList">
        <md-checkbox 
           name="{{x.maintenancetype}}" 
           value="{{x.maintenancetype}}"  
           [formControl]="CreateSocietyForm.controls['checkMaintainanceType']">
             {{x.maintenancetype}}
        </md-checkbox>
    </span>