1

This is my html. I want to get the value of all selected checkbox when any checkbox is checked or unchecked i.e (change) event fired

<div class="checkbox checkbox-primary" *ngFor="let category of categories; let i = index">
     <input type="checkbox" id="checkbox_category"  (change)="search(category, $event)" />
 </div>

This is my search method in angular 2 component :

selectedItems: any = [];
search( category, event) {

   // set selectedItems here
}

2 Answers 2

1

You can do something like this: https://plnkr.co/edit/94Gubz?p=preview

  @Component({
  selector: 'my-app',
  template: `
    <div class="checkbox checkbox-primary" *ngFor="let category of categories; let i = index">
     <input type="checkbox" id="checkbox_category" [checked]="category.selected" (click)="select(i)"  /> {{category.value}}
 </div>
  `,
})
export class App {
  categories: any;
  selected: any;

  constructor() {
    this.categories = [
        {value: 'ferrari', selected: false },
        {value: 'porche', selected: false },
        {value: 'bentley', selected: false }
        ];
      }

  select(index) {
    this.categories[index].selected = !this.categories[index].selected
  }

  search() {
    this.selected = this.categories.filter(cat => cat.selected)
  }

}
Sign up to request clarification or add additional context in comments.

Comments

1

I solved the problem like this : https://plnkr.co/edit/mWtlkydF0FzioS3c2esQ?p=preview

@Component({
selector: 'my-app',
template: `
<div class="checkbox checkbox-primary" *ngFor="let category of categories; let i = index">
     <input type="checkbox"  id="checkbox_category_{{i}}" (change)="search(category, $event)" />
     <label> {{category?.name }} </label>
</div>

<b>selectedItems</b>: {{selectedItems | json}}
`,
})
export class App {

  categories: any;
  selectedItems: any = [];

  constructor() {
    this.getData();
  }

  //this data may come from api
  getData(){

  this.categories = [
        {name: 'ferrari', price: 123},
        {name: 'porche', price: 456},
        {name: 'bentley', price: 789}
        ];
  }

  search(category, event) {

        var index = this.selectedItems.indexOf(category.name);
        if (event.target.checked) {
            if (index === -1) {
                this.selectedItems.push(category.name);
            }
        } else {
            if (index !== -1) {
                this.selectedItems.splice(index, 1);
            }
        }
        console.log(this.selectedItems);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.