Angular 4 Getting values ​​from checkboxes

I am new to angular and am stuck with this rather simple problem. I am getting data from a web service to show a couple of checkboxes. I need a way to get the value of all 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>

      

+3


source to share


2 answers


You can add event change

to md-checkbox

and pass the function object. Maintain array

which keeps track of which ones got checked

and unchecked

, and update the array accordingly.

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

+6


source


e.checked

You can use the following instead :

Working example



<input class="form-check-input" type="checkbox" (change)="selectBadge($event, badge._id)"> <span class="badge badge-pill {{badge.color}}">{{badge.text}}</span>

selectBadge (e, id) {

if (e.target.checked) {

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

      

0


source







All Articles