因为工作原因,需要使用到checkbox list多选项功能。

一直在尝试在checkbox组件中添加NgModel的属性,但是只能在单个checkbox复选框上使用,checkbox list就没办法了。

好吧,其实是想差了。

因为是对checkbox的div添加ngFor的循环,所以每个checkbox都相当于list中的item,直接在item的属性,多加一个checked就好了,然后使用选中的list时filter checked==true就好了。

checkbox-list.component.html

  1. 1 <div *ngIf="list" class="form-row">
  2. 2 <div class="col-{{colNum}} mb-2" *ngFor="let item of list">
  3. 3 <div class="form-check abc-checkbox abc-checkbox-primary">
  4. 4 <input class="form-check-input" type="checkbox" [value]="item.id" [(ngModel)]="item.checked" (change)="changeSelected()" id="{{name}}_{{item.id}}">
  5. 5 <label class="form-check-label" for="{{name}}_{{item.id}}">
  6. 6 {{item.name}}
  7. 7 </label>
  8. 8 </div>
  9. 9 </div>
  10. 10 </div>

checkbox-list.component.ts

  1. 1 import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
  2. 2 import { CheckboxItem } from '../../model/checkbox';
  3. 3 import { NgModel } from '@angular/forms';
  4. 4 import { filter } from 'rxjs/operator/filter';
  5. 5
  6. 6 @Component({
  7. 7 selector: 'app-checkbox-list',
  8. 8 templateUrl: './checkbox-list.component.html',
  9. 9 styleUrls: ['./checkbox-list.component.css']
  10. 10 })
  11. 11 export class CheckboxListComponent implements OnInit {
  12. 12 @Input() list: CheckboxItem[];
  13. 13 @Input() name: string;
  14. 14 @Input() colNum: number = 6;
  15. 15 @Output("selectChange") onChange: EventEmitter<any> = new EventEmitter<any>();
  16. 16
  17. 17 constructor() { }
  18. 18
  19. 19 ngOnInit() {
  20. 20 }
  21. 21 changeSelected() {
  22. 22 let filters = this.list.filter(x => x.checked);
  23. 23 let ids = [] as any[];
  24. 24 for (var i = 0; i < filters.length; i++) {
  25. 25 ids.push(filters[i].id);
  26. 26 }
  27. 27
  28. 28 this.onChange.emit({ value: ids, name: this.name });
  29. 29 }
  30. 30 }

 

使用的时候,直接在module中添加引用:

  1. 1 import { NgModule } from '@angular/core';
  2. 2 import { CommonModule } from '@angular/common';
  3. 3 import { FormsModule } from '@angular/forms';
  4. 4
  5. 5 import { CheckboxListComponent } from '../components/checkbox-list/checkbox-list.component';
  6. 6 ......
  7. 7 export const routes = [
  8. 8 { path: '', component: OrderBuyDataComponent, pathMatch: 'full' }
  9. 9 ];
  10. 10
  11. 11
  12. 12 @NgModule({
  13. 13 imports: [FormsModule
  14. 14 , CommonModule
  15. 15 , ...],
  16. 16 declarations: [CheckboxListComponent
  17. 17 , ...],
  18. 18 providers: []
  19. 19 })
  20. 20 export class OrderModule {
  21. 21 static routes = routes;
  22. 22 }

因为写的比较仓促,所以一些代码还没整理好。

 

版权声明:本文为bu-dong原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/bu-dong/p/9276521.html