日期选取器"在类型"JQuery "上不存在



我正在尝试对 ag-grid 的日期字段列实现内联编辑。我指的是以下 ag-grid 文档,并设法在网格中包含日期选择器,但是我的应用程序日期选择器中出现编译时错误,类型"JQuery"上不存在。我正在使用 ag-grid 社区版和 Angular 7 应用程序。

这是堆叠

https://stackblitz.com/edit/angular-cjvfx2

我已经安装了以下内容

npm install Jquery
npm install --save @types/jquery

已将以下条目添加到 angular.json

 "scripts": [ "./node_modules/jquery/dist/jquery.js"]

元件

import { Component, Injectable, NgZone, ViewEncapsulation, ViewChild, Input } from '@angular/core'
import { OnInit } from '@angular/core'
import { Comparator } from '../utilities/comparator';
import { GridOptions, GridApi } from 'ag-grid-community';
import { DocumentUploadService } from '../services/documentUpload.service';
import { NotifyService } from '../utilities/notify.service';
import { number } from '@amcharts/amcharts4/core';
import * as jquery from 'jquery';

function getDatePicker() {
    function Datepicker() {}
    Datepicker.prototype.init = function(params) {
      this.eInput = document.createElement("input");
      this.eInput.value = params.value;
      $(this.eInput).datepicker({ dateFormat: "dd/mm/yy" });
    };
    Datepicker.prototype.getGui = function() {
      return this.eInput;
    };
    Datepicker.prototype.afterGuiAttached = function() {
      this.eInput.focus();
      this.eInput.select();
    };
    Datepicker.prototype.getValue = function() {
      return this.eInput.value;
    };
    Datepicker.prototype.destroy = function() {};
    Datepicker.prototype.isPopup = function() {
      return false;
    };
    return Datepicker;
  }


@Component({
    selector: 'mgr-document-upload',
    templateUrl: './documentUpload.component.html'
})

export class DocumentUploadComponent implements OnInit {
    Files: Array<File>;
    ColumnDefs: Array<any> = new Array<any>();
    private Comparator: Comparator;
    private Error: string;
    private gridApi: GridApi;
    public GridOptions: GridOptions;
    private editClicked;
    private editingRowIndex;
    private editType;
    private components;
    ngZone: any;
    windowHeight: any;
    offset: number;
    Loading: boolean;
    public DocumentUploadDetails: any;
    public params: any;
    @Input() ManagerStrategyId = 5508;
    MgrStrategyId = 5508;

    ngOnInit() {
        this.setGridOptions();
        this.getDocumentUploadDetails();
    }

    constructor(private comparator: Comparator, private documentUploadService : DocumentUploadService,  private notify: NotifyService,) {
        this.Comparator = comparator;
        this.editClicked = true;
        this.getDocumentUploadDetails();
        window.onresize = (e) => {
            this.ngZone.run(() => {
                this.windowHeight = window.innerHeight - this.offset;
                setTimeout(() => {
                    if (!this.GridOptions || !this.GridOptions.api) {
                        return;
                    }
                }, 500, true);
            });
        };
    }

    private getColumns(): Array<any> {
        const self = this;
        const columnDefs = new Array<any>();
        columnDefs.push({ headerName: 'ID', field: 'DocumentId', hide: true ,editable: false});
        columnDefs.push({ headerName: 'Document Type ID', field: 'DocumentTypeId', hide: true , editable: false});
        columnDefs.push({ headerName: 'Type', field: 'DocumentTypeName', hide: false , editable: true ,  cellEditor: 'agSelectCellEditor',
        cellEditorParams: {
          values: this.DocumentUploadDetails.DocumentTypes,
          cellRenderer: (params) => params.value.Name
        }
    });
        columnDefs.push({ headerName: 'Document', field: 'DocumentName', hide: false, editable: true });
        columnDefs.push({ headerName: 'Document Date', field: 'DocumentDate', hide: false , editable: true,   cellEditor: 'datePicker'});
        columnDefs.push(
            {
                cellRenderer: function (p) {
                    if (p.node.data && p.node.data.DocumentId) {
                        var eSpan = self.getDeleteSpan();
                        eSpan.addEventListener('click', function () {
                            var self2 = self;
                            //self2.onEdit();
                        });
                        return eSpan;
                    }
                    else {
                        return '';
                    }
                }, comparator: this.comparator.StringComparator, width: 50, cellStyle: { textAlign: 'center' }, cellClass: 'align-center', headerName: "Edit", pinned: 'right'
            });

        columnDefs.push(
            {
                cellRenderer: function (p) {
                    if (p.node.data && p.node.data.DocumentId) {
                        var eSpan = self.getDeleteSpan();
                        eSpan.addEventListener('click', function () {
                            var self2 = self;
                            self2.Delete(p.node.data.DocumentId);
                        });
                        return eSpan;
                    }
                    else {
                        return '';
                    }
                }, comparator: this.comparator.StringComparator, width: 50, cellStyle: { textAlign: 'center' }, cellClass: 'align-center', headerName: "Delete", pinned: 'right'
            });
            this.components = { datePicker: getDatePicker() };
            this.editType = 'fullRow';
        return columnDefs;
    }

    onEdit() {
        // this.params =  this.GridOptions.api.getEditingCells;
        // this.editClicked = !this.editClicked;
        // this.params.api.setFocusedCell(this.params.node.rowIndex, 'action');
        // this.params.api.startEditingCell({
        //  rowIndex: this.params.node.rowIndex,
        //  colKey: 'action'
        // });
       }

    private getDeleteSpan() {
        var eSpan = document.createElement('a');
        eSpan.innerHTML = '<div style="cursor:pointer;max-width: 50px"><i class="far fa-trash-alt fontColor" aria-hidden="true"></i></div>';
        return eSpan;
    }

    GridHeight() {
        if (!this.windowHeight) {
            this.windowHeight = window.innerHeight - this.offset + 10;
        }
        return this.windowHeight;
    }
    private initGrid() {
        const self = this;
    }
    setGridOptions() {
        this.GridOptions = {
            columnDefs: this.getColumns(),
            enableFilter: true,
            enableColResize: true,
            animateRows: true,
            enableSorting: true,
            onGridReady: e => {
                if (!e || !e.api) {
                    return;
                }
                this.gridApi = e.api;
                this.setDefaultSortOrder();
            },
            onGridSizeChanged: () => this.GridOptions.api.sizeColumnsToFit(),

        };
    }
    onCellClicked($event){
        // check whether the current row is already opened in edit or not
        if(this.editingRowIndex != $event.rowIndex) {
          console.log($event);
          $event.api.startEditingCell({
            rowIndex: $event.rowIndex,
            colKey: $event.column.colId
          });
          this.editingRowIndex = $event.rowIndex;
        }
      }
    setDefaultSortOrder() {
        const defaultSortModel = [
            { colId: 'DocumentDate', sort: 'desc' }
        ];
        this.GridOptions.api.setSortModel(defaultSortModel);
    }

    onGridSizeChanged(params) {
        const gridWidth = document.getElementById('grid-wrapper').offsetWidth;
        const columnsToShow = [];
        const columnsToHide = [];
        let totalColsWidth = 0;
        const allColumns = params.columnApi.getAllColumns();
        for (let i = 0; i < allColumns.length; i++) {
            const column = allColumns[i];
            totalColsWidth += column.getMinWidth();
            if (totalColsWidth > gridWidth) {
                columnsToHide.push(column.colId);
            } else {
                columnsToShow.push(column.colId);
            }
        }
        params.columnApi.setColumnsVisible(columnsToShow, true);
        params.columnApi.setColumnsVisible(columnsToHide, false);
        params.api.sizeColumnsToFit();
    }
    private Delete(Id: number) {
            if (Id !== 0) {

                this.Error = '';
                this.documentUploadService
                    .deleteDocument(Id)
                    .then((result) => {
                        if (result) {
                            this.notify.success('Document Successfully Deleted');
                           // this.ClassficationOverrideDetailsEvent.next('init');
                        }
                    }).catch(err => {
                        this.notify.error('An Error Has Occured While Deleting Document');
                    });
            }
    }


    public getDocumentUploadDetails() {
        if (this.MgrStrategyId != null) {
            this.Loading = true;
            this.initGrid();
            //  this.spinner.show();
            this.documentUploadService.getDocumentUploadDetails(this.MgrStrategyId)
                .subscribe(data => {
                    this.DocumentUploadDetails = data;
                    this.ColumnDefs = this.getColumns();
                    this.Loading = false;
                    setTimeout(() => {
                        this.GridOptions.api.sizeColumnsToFit();
                        this.Loading = false;
                    }, 100, true);
                },
                    err => {
                        this.Error = 'An error has occurred. Please contact BSG';
                    },
                    () => {
                    });
        }
    }
}

目录

<div class="card" *ngIf="DocumentUploadDetails && DocumentUploadDetails.DocumentEntities" style="margin-top: 10px" >
    <div class="card-body" style="width:100%; text-align: left;">
        <div style="overflow-x: hidden; overflow-y: hidden; ">
            <div class="form-group row">
                <div class="panel panel-default col-md-12  ">
                    <div class="panel-body">
                        <div id="grid-wrapper" [style.height.px]="GridHeight()" [style.width.%]="100"
                            style="float: left;">
                            <ag-grid-angular #agGrid class="ag-theme-balham" [gridOptions]="GridOptions"
                                style="width: 100%; height: 100%" [columnDefs]="ColumnDefs" rowHeight="30"
                                [rowData]="DocumentUploadDetails.DocumentEntities"
                                [editType]="editType"
                                (cellClicked)="onCellClicked($event)"
                                headerHeight="30" rowSelection="single">
                            </ag-grid-angular>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

尝试安装:jquery-datepicker

npm i jquery-datepicker -s

然后,添加到 app.components.ts:

import datepickerFactory from 'jquery-datepicker';
import datepickerJAFactory from 'jquery-datepicker/i18n/jquery.ui.datepicker-en-GB';
declare const $: any; // avoid the error on $(this.eInput).datepicker();
datepickerFactory($);
datepickerJAFactory($);

Angular.json

"scripts": [ "./node_modules/jquery/dist/jquery.js"]

你能根据这个问题提供更多信息吗?

  1. 在package.json上jQuery并查看node_modules文件夹,确保jQuery中有DatePicker。

  2. 检查 tsconfig.app.json 您是否添加了 jquery 类型?

{
   ...
   "compilerOptions": {
       "outDir": "./out-tsc/app",
       "types": []
    },
   ...
}
  1. 如果是。你能在页面上记录jquery以查看它是否可用于日期选择器吗?

这是我的建议:

使用角度材质显示日期选取器。有关更多详细信息,请阅读以下文档链接:https://material.angular.io/components/datepicker/overview

安装npm install --save @angular/material @angular/cdk @angular/animations

如何应用到您的代码中:

import {MatDatepickerModule} from '@angular/material/datepicker'
...
<mat-form-field class="example-full-width">
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker">
    <mat-icon matDatepickerToggleIcon>keyboard_arrow_down</mat-icon>
  </mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

相关内容

最新更新