0

I'm using multiple checkboxes and on click of any of the checkbox need to push the value in array if it is checked true and remove from the array if checked false.

Is there any way to check that the checkbox is checked or unchecked on a click like jquery?

Madhuri
  • 23
  • 1
  • 8
  • You can try using eventEmiiter `(click)` like this `(click)=onClick($event.checked)`. Gives true when checked and false on uncheck – Sumit Agarwal Oct 27 '16 at 07:48
  • can u explain in more detail with more code , coz i used the onclick event its showing undefined. does $event needs anything to import any class ?? – Madhuri Oct 27 '16 at 07:53

2 Answers2

0

Further to the comment:

HTML Element:

<input type="checkbox" (click)="onClick($event)" />

TypeScript Code:

onClick(event: any) {
 console.log(event); //you can explore the event object and use the values as per requirement
}
Sumit Agarwal
  • 4,091
  • 8
  • 33
  • 49
  • i used event.target.checked which should return true or false but still giving undefined am i missing anything , help will be appreciated – Madhuri Oct 27 '16 at 09:52
0

Check this similar post that solves the issue for multiple checkboxes. angular-2-get-values-of-multiple-checked-checkboxes

I have included here a simple implementation for checkbox states in angular2

import {Component, NgModule } from '@angular/core';

@Component({
  selector: 'test-app',
  template: `
    <label for="options">Options :</label>
    <div *ngFor="let cbItem of cbArr">
      <label>
        <input type="checkbox"
               name="options"
               value="{{cbItem}}"
               [checked]="cbChecked.indexOf(cbItem) >= 0"
               (change)="updateCheckedOptions(cbItem, $event)"/>
        {{cbItem}}
      </label>
    </div>
    <button (click)="updateOptions()">Post</button>
  `
})
export class TestComponent{
    cbArr: string[];
    cbChecked: string[];
  constructor() {
    this.cbArr = ['OptionA', 'OptionB', 'OptionC'];
    this.cbChecked = ['OptionB'];
  }
  
  updateCheckedOptions(chBox, event) {
      var cbIdx = this.cbChecked.indexOf(chBox);
      if(event.target.checked) {
          if(cbIdx < 0 )
            this.cbChecked.push(chBox);
      } else {
          if(cbIdx >= 0 )
            this.cbChecked.splice(cbIdx,1);
      }
  }
  
  updateOptions() {
    console.log(this.cbChecked);
  }
  
}

Here cbArr stores the values or options needed and cbChecked stores the selected values. On changing the checkbox value, cbChecked is updated id checkbox item is updated into it and finally on click of "Post" button, you can simply print out the cbChecked values for the list of items under selection.

Community
  • 1
  • 1
Ashwin Kumar
  • 711
  • 5
  • 6