Angular中ag-grid日期单元格编辑添加mydatepicker日期选择器的问题
ag-grid自定义日期编辑器集成mydatepicker实现方案
1. 实现自定义ag-grid编辑器组件
自定义编辑器需要实现ag-grid提供的ICellEditorAngularComp接口,适配mydatepicker的传参和返回值逻辑:
import { Component } from '@angular/core'; import { ICellEditorAngularComp } from 'ag-grid-angular'; import { IMyOptions, IMyDateModel } from 'mydatepicker'; @Component({ selector: 'app-ag-grid-date-editor', template: ` <my-date-picker [options]="datePickerOptions" [(ngModel)]="selectedDate" (dateChanged)="handleDateChange($event)"> </my-date-picker> ` }) export class AgGridDateEditorComponent implements ICellEditorAngularComp { params: any; selectedDate: any; // 配置直接对齐项目其他模块在用的mydatepicker配置即可 datePickerOptions: IMyOptions = { dateFormat: 'yyyy-mm-dd', showTodayBtn: true, // 其余自定义配置按项目需求补充 }; agInit(params: any): void { this.params = params; // 初始化单元格已有日期值 if (params.value) { const rawDate = new Date(params.value); this.selectedDate = { date: { year: rawDate.getFullYear(), month: rawDate.getMonth() + 1, day: rawDate.getDate() } }; } } handleDateChange(event: IMyDateModel): void { // 选中后自动关闭编辑状态,不需要可删除 this.params.api.stopEditing(); } // 返回最终写入单元格的日期值,格式按项目需求调整 getValue(): any { if (!this.selectedDate?.date) return null; return new Date( this.selectedDate.date.year, this.selectedDate.date.month - 1, this.selectedDate.date.day ).toISOString().slice(0, 10); } }
2. 注册自定义编辑器
在使用ag-grid的对应Angular模块中注册组件:
- 在
declarations数组中加入AgGridDateEditorComponent - Angular版本低于9的项目需要额外在
entryComponents数组中加入AgGridDateEditorComponent,9+开启Ivy的版本不需要该配置
3. 列配置中绑定编辑器
在日期列的定义中指定自定义编辑器即可生效:
const columnDefs = [ // 其他列配置 { field: 'yourDateField', headerName: '日期', editable: true, cellEditor: 'datePickerEditor', // 非编辑状态日期格式化,按需调整 valueFormatter: (params) => params.value ? new Date(params.value).toLocaleDateString() : '-', } ]; public gridOptions = { columnDefs, // 注册编辑器映射 components: { datePickerEditor: AgGridDateEditorComponent }, // 其余grid配置 }
适配说明
- 如果项目用的日期值是时间戳、自定义字符串等格式,只需要修改
agInit的初始化逻辑和getValue的返回值逻辑即可适配 - 不需要弹出选择器后自动结束编辑的,删除
handleDateChange里的stopEditing调用即可
内容的提问来源于stack exchange,提问作者JustCoder
相关产品推荐
相关产品推荐

