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()" id="{{name}}_{{item.id}}"> 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 }
因为写的比较仓促,所以一些代码还没整理好。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库