Angular5中提取公共组件之checkbox list

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

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

好吧,其实是想差了。

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

checkbox-list.component.html

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

checkbox-list.component.ts

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

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

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

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