如何动态创建复选框并获取角度2中所有选中复选框的值

时间:2017-02-18 05:41:52

标签: html angular checkbox

这是我的HTML。我想在选中或取消选中任何复选框时获取所有选中复选框的值,即(更改)事件触发

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

这是我在角度2组件中的搜索方法:

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

   // set selectedItems here
}

2 个答案:

答案 0 :(得分:1)

您可以这样做: 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)
  }

}

答案 1 :(得分:1)

我解决了这样的问题: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 {
  name:string;
  categories: any;
  selectedItems: any = [];

  constructor() {
    this.name = 'Angular2';
    this.getDate();
  }

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

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