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);
}
}