在Ag-grid Angular中,单击日期选择器后,如果将焦点从单元格编辑器移动,可能会导致日期选择器关闭。为了解决这个问题,可以使用以下代码示例:
import { Component } from '@angular/core';
import { GridOptions } from 'ag-grid-community';
import { DatepickerComponent } from './datepicker.component';
import { MatDialog } from '@angular/material';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
private gridOptions: GridOptions;
private datePicker: DatepickerComponent;
constructor(private dialog: MatDialog) {
this.gridOptions = {};
this.gridOptions.columnDefs = [
{headerName: 'Date', field: 'date', editable: true, cellEditor: 'datePicker'}
];
this.gridOptions.components = {
datePicker: this.getDatePicker()
};
}
private getDatePicker() {
return {
template: '',
init: function(params) {
this.params = params;
this.value = this.params.value;
this.inputElement = document.createElement('input');
this.inputElement.value = this.value;
this.inputElement.classList.add('ag-input');
this.inputElement.style.width = '100%';
this.inputElement.style.height = '100%';
this.inputElement.style.boxSizing = 'border-box';
this.inputElement.addEventListener('blur', () => {
if (this.datePicker) {
setTimeout(() => {
if (!this.datePicker.opened) {
this.params.api.stopEditing();
}
})
}
});
this.inputElement.addEventListener('click', () => {
if (this.datePicker) {
this.datePicker.open();
}
});
},
getGui: function() {
return this.inputElement;
},
afterGuiAttached: function() {
this.inputElement.focus();
this.inputElement.select();
},
getValue: function() {
return this.inputElement.value;
},
isPopup: function() {
return true;
},
onClick: function(event) {
event.stopPropagation();
if (!this.datePicker) {
const dialogRef = this.dialog.open(DatepickerComponent, {
data: {date: this.value},
panelClass: 'ag-grid-datepicker-dialog'
});
this.datePicker = dialogRef.componentInstance;
dialogRef.afterClosed().subscribe(result => {
this.datePicker = null;
if (result) {
this.inputElement.value = result;
}