datepicker”在类型“ JQuery

时间:2019-06-19 11:57:16

标签: angular ag-grid

我正在尝试对ag-grid的日期字段列进行内联编辑。我指的是以下有关ag-grid的文档,并已在网格中包括了datepicker,但是我的应用程序datepicker中出现编译时错误,类型'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';
                    },
                    () => {
                    });
        }
    }
}

HTML

<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>

3 个答案:

答案 0 :(得分:3)

尝试安装: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 :(得分:1)

这是我的建议:

使用Angular材质显示日期选择器。阅读以下文档链接以获取更多详细信息: 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>

答案 2 :(得分:0)

您能否提供有关此问题的更多信息?

    在package.json上的
  1. jquery并查看node_modules文件夹,确保jquery中有datepicker。

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

{
   ...
   "compilerOptions": {
       "outDir": "./out-tsc/app",
       "types": []
    },
   ...
}
  1. 如果是。您能否在页面上记录jquery以查看它是否可以与datepicker一起使用?