Angular5中提取公共组件之checkbox list

时间:2023-03-09 09:50:15
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

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

checkbox-list.component.ts

 import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { CheckboxItem } from '../../model/checkbox';
import { NgModel } from '@angular/forms';
import { filter } from 'rxjs/operator/filter'; @Component({
selector: 'app-checkbox-list',
templateUrl: './checkbox-list.component.html',
styleUrls: ['./checkbox-list.component.css']
})
export class CheckboxListComponent implements OnInit {
@Input() list: CheckboxItem[];
@Input() name: string;
@Input() colNum: number = 6;
@Output("selectChange") onChange: EventEmitter<any> = new EventEmitter<any>(); constructor() { } ngOnInit() {
}
changeSelected() {
let filters = this.list.filter(x => x.checked);
let ids = [] as any[];
for (var i = 0; i < filters.length; i++) {
ids.push(filters[i].id);
} this.onChange.emit({ value: ids, name: this.name });
}
}

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

 import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms'; import { CheckboxListComponent } from '../components/checkbox-list/checkbox-list.component';
......
export const routes = [
{ path: '', component: OrderBuyDataComponent, pathMatch: 'full' }
]; @NgModule({
imports: [FormsModule
, CommonModule
, ...],
declarations: [CheckboxListComponent
, ...],
providers: []
})
export class OrderModule {
static routes = routes;
}

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