Angular9+Bootstrap v6.0.2实现ng-bootstrap日期选择器离散多日期选中
ng-bootstrap datepicker 离散多日期选择实现方案
实现思路
- 放弃组件自带的单选双向绑定逻辑,自行维护选中日期数组
- 点击日期时判断该日期是否已在选中数组中,执行新增/移除操作
- 自定义日期格子的选中样式,绑定自行实现的选中判断逻辑
1. 修改 datepicker.component.ts 代码
import { NgbDateStruct, NgbDate, NgbCalendar } from '@ng-bootstrap/ng-bootstrap'; import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-datepicker', templateUrl: './datepicker.component.html' }) export class DatepickerComponent { // 替换原单日期变量,用数组存储所有选中日期 selectedDates: NgbDate[] = []; @Output() selectedDateEventEmitter = new EventEmitter<NgbDate[]>(); @Input() minDate: NgbDateStruct; @Input() maxDate: NgbDateStruct; constructor(private calendar: NgbCalendar) { } ngOnInit(): void { } onDateSelection(date: NgbDate) { // 查找当前点击日期是否已存在于选中数组 const existedIndex = this.selectedDates.findIndex(item => item.equals(date)); if (existedIndex > -1) { // 已选中则移除该日期 this.selectedDates.splice(existedIndex, 1); } else { // 未选中则加入数组 this.selectedDates.push(date); } // 向外输出所有选中的日期数组 this.selectedDateEventEmitter.emit(this.selectedDates); } isWeekend(date: NgbDateStruct) { const d = new Date(date.year, date.month - 1, date.day); return d.getDay() === 0 || d.getDay() === 6; } isDisabled = (date: NgbDateStruct, current: { month: number }) => { return this.isWeekend(date); } // 新增日期选中状态判断方法 isSelected(date: NgbDate): boolean { return this.selectedDates.some(item => item.equals(date)); } }
2. 修改 datepicker.component.html 代码
<ngb-datepicker class="datepicker-custom" [dayTemplate]="dayTemplate" [minDate]="minDate" [maxDate]="maxDate" [markDisabled]="isDisabled" (dateSelect)="onDateSelection($event)"> </ngb-datepicker> <ng-template #dayTemplate let-date let-currentMonth="currentMonth" let-disabled="disabled" let-focused="focused"> <div ngbdatepickerdayview class="custom-day btn-light" [class.weekend]="isWeekend(date)" [class.focused]="focused" <!-- 替换原生selected属性,用自定义方法判断选中状态 --> [class.bg-primary.text-white]="isSelected(date)" [class.hidden]="date.month !== currentMonth" [class.text-muted]="disabled"> <span>{{ date.day }}</span> </div> </ng-template>
修改后点击日期即可自动切换选中状态,支持同时选中多个不连续的日期,父组件可监听selectedDateEventEmitter事件拿到所有选中的日期数组。
内容的提问来源于stack exchange,提问作者Mourad9
相关产品推荐
相关产品推荐

