angular中ag-grid实战

把ag-grid做成了组件,去掉了自带的列组件

ag-gird官网:
https://www.ag-grid.com/documentation/angular/getting-started/#customise-the-theme-look

module.ts中导入这两行

import { AgGridModule } from 'ag-grid-angular';
import 'ag-grid-enterprise';

angular中ag-grid实战_第1张图片

组件代码,自己做的分页和自定义列,上代码

html:

<ag-grid-angular
    style="width: 100%; height: calc(100% - 55px);margin-bottom: 10px;"
    #agGrid
    class="ag-theme-alpine"
    [suppressRowClickSelection]="true"
    [allowDragFromColumnsToolPanel]="true"
    [suppressContextMenu]="suppressContextMenu"
    [overlayLoadingTemplate]="overlayLoadingTemplate"
    [overlayNoRowsTemplate]="overlayNoRowsTemplate"
    [gridOptions]="gridOptions"
    [rowData]="rowData.nzData"
    [columnDefs]="columnDefs"
    [frameworkComponents]="frameworkComponents"
    [defaultColDef]="defaultColDef"
    [getContextMenuItems]="getContextMenuItems"
    (dragStopped)="dragStopped($event)"
>
</ag-grid-angular>
//NG_ZORRO分页组件,
<nz-pagination class="text-right" 
    [(nzPageIndex)]="rowData.nzPageIndex" 
    [nzTotal]="rowData.nzTotal" 
    [(nzPageSize)]="rowData.nzPageSize" 
    [nzSize]="'small'" 
    [nzShowTotal]="showTotalTemplate" 
    (nzPageIndexChange)="refresh()"
    (nzPageSizeChange)="refresh()"
    nzShowSizeChanger 
    nzShowQuickJumper>
</nz-pagination>
<ng-template #showTotalTemplate let-total let-range="range">
    当前 {{rowData.nzPageIndex}}/{{rowData.totalPages}} 页,共 {{total}}/显示 {{range[0]}}-{{range[1]}}</ng-template>
//自己写的自定义列组件
<app-user-defined-column 
*ngIf="isUserDefinedColumn" 
[dataColumnConfig]="columnConfig" 
(isUserDefined)="isDefinedColumn($event)" 
[definedColumn]="columnDefs"
></app-user-defined-column>

ts:

import { HttpClient, HttpHeaders, HttpResponse } from "@angular/common/http";
import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from "@angular/core";
import { ButtonColumnRenderer } from "@shared/agGrid-renderer/button-column/button-column.component";
import { LoadImgColumnRenderer } from "@shared/agGrid-renderer/loadImg-column/loadImg-column.component";
import { TooltipColumnRenderer } from "@shared/agGrid-renderer/tooltip-column/tooltip-column.component";
import { BackCustomerHeaderServiceProxy, ComplaintFDto, CustomerHeaderCreateUpdateFDto, ExportModel } from "@shared/service-proxies/up-middle-service-proxies";
import { AppSessionService } from "@shared/session/app-session.service";
import { AgGridAngular } from "ag-grid-angular";
import { GridOptions } from "ag-grid-community";
import { NzMessageService } from "ng-zorro-antd";

@Component({
    selector: "ag-grid-single",
    templateUrl: "ag-grid-single.component.html",
    styleUrls: ["ag-grid-single.component.scss"]
})
export class AgGridSingleComponent implements OnInit  {
    @ViewChild('agGrid') agGrid: AgGridAngular;

    @Input() rowData :any; //数据源
    @Input() columnDefs:any;//grid 列配置
    @Output() exportDataAsExcel = new EventEmitter<any>(); //导出数据到Excel接收的方法
    @Output() rowRefresh = new EventEmitter<any>(); // 数据刷新

    defaultColDef = {
        sortable: true,
        resizable: true,
        suppressMenu: true,
    };
    gridOptions: any;
    frameworkComponents: any;
    overlayLoadingTemplate: string;
    overlayNoRowsTemplate: string;
    titleGroupName:any;
    isUserDefinedColumn: boolean = false;
    suppressContextMenu: boolean = false;
    columnConfig:any;
    constructor(
        private nzmessage: NzMessageService,
        private appSession: AppSessionService,
        private backCustomerHeaderService: BackCustomerHeaderServiceProxy,
        private http: HttpClient,
    ) {
        this.frameworkComponents = {
            buttonRenderer: ButtonColumnRenderer,
            tooltipRenderer: TooltipColumnRenderer,
            loadImgRenderer: LoadImgColumnRenderer,
          };
        this.overlayLoadingTemplate =
          '加载中,请稍等...';
        this.overlayNoRowsTemplate =
          '暂无数据';
        // sideBar = {
        //     toolPanels: [
        //         {
        //             id: 'columns',
        //             labelDefault: '列选择器',
        //             labelKey: 'columns',
        //             iconKey: 'columns',
        //             toolPanel: 'agColumnsToolPanel',
        //             toolPanelParams: {
        //                 suppressRowGroups: true,
        //                 suppressValues: true,
        //                 suppressPivots: true,
        //                 suppressPivotMode: true,
        //               },
        //         }
        //     ]
        // };
    }
    async ngOnInit() {
        //初始
      this.suppressContextMenu = !this.rowData.gridId;
      this.gridOptions = <GridOptions>{
        context: {
            savecol: this.saveColType.bind(this)
        }
      };
      if (this.exportDataAsExcel.observers.length) {
        this.gridOptions = <GridOptions>{
          context: {
              savecol: this.saveColType.bind(this),
              exportfun: this.export.bind(this)
          }
        };
      } 
    }
    //设置grid右键菜单
    getContextMenuItems(params) {
        let result = [
          {
            name: '导出(.xls)',
            action: function () {
            //   window.alert('导出Excel功能待实现');
              params.context.exportfun();
            
            },
          },
          {
            name: '自动调整列宽',
            action: function () {
              params.columnApi.autoSizeAllColumns();
            },
          },
          'separator',
          {
            name: '保存自定义列',
            action: function () {
                params.api.showLoadingOverlay();
                params.context.savecol();
                params.api.hideOverlay();
            },
          },
          {
            name: '恢复默认列',
            action: function () {
              params.columnApi.resetColumnState();
            },
          },
        ];
        //如果export方法没有传入,则去掉导出按钮
        if (!params.context.exportfun) {
          result.shift();
        }
        return result;
      }
    async saveColType(){
        let params : CustomerHeaderCreateUpdateFDto = new CustomerHeaderCreateUpdateFDto();
        params.data = JSON.stringify(this.agGrid.columnApi.getColumnState());
        params.moduleName = this.rowData.gridId;
        params.userId = this.appSession.user.id;
        params.isDeleted = false;
        params.status = 1;
        params.version = 10;
        let result = await this.backCustomerHeaderService.insert(params).toPromise();
        if (result.success) {
            this.nzmessage.success('自定义列保存成功');
        }
    }
    isDefinedColumn(val:any){
        this.isUserDefinedColumn = false;
        if (val) {
          this.agGrid.columnApi.applyColumnState({state: val, applyOrder: true});
          this.saveColType();
        }
      }
      openmadol(){
        this.columnConfig = this.userColumn();
        this.isUserDefinedColumn=true;
      }
    	//为自定义列组件数据做处理
      userColumn(){
        let rowState = this.agGrid.columnApi.getColumnState();
        rowState.map(item=>{
          const col = this.columnDefs.filter(row=>{
            return row.field == item.colId;
          })
          if (col && col.length>0) {
            item['colName'] = col[0].headerName;
            if (col[0].suppressColumnsToolPanel) {
                item['required'] = true;
            }
          }
        });
        return rowState;
      }
    async ngAfterViewInit(){
    	//请求接口获取自定义列设置
        let result = await this.backCustomerHeaderService.get(this.rowData.gridId).toPromise();
        if (result.success) {
            let colType = result.data;
            if (colType && JSON.parse(colType)) {
                this.agGrid.columnApi.applyColumnState({state: JSON.parse(colType), applyOrder: true});
            }
        }
    }
    getSelectedRows() {
        const selectedNodes = this.agGrid.api.getSelectedNodes();
        const selectedData = selectedNodes.map(node => node.data );
        const selectedDataStringPresentation = selectedData.map(node => node.name + ' ' + node.phoneNumber).join(', ');
    }
    export(){
       this.exportDataAsExcel.emit();
    }

    //列移动结束后 操作列放在第一个位置
    dragStopped(e){
      let cloumns = e.columnApi.getColumnState();
      if (cloumns[0].colId != "operation") {
        e.columnApi.moveColumn("operation", 0);
      }
    }

    // 导出
    exportAsExcel(params:any,url:string) {
       this.agGrid.api.showLoadingOverlay();
       let group2: any = this.agGrid.columnApi.getLeftDisplayedColumnGroups();
       let exportconfig = this.gridapilist(group2);
       let group1: any = this.agGrid.columnApi.getCenterDisplayedColumnGroups();
       let colHarder = exportconfig.concat(this.gridapilist(group1));
       params.exportModel = colHarder;
       let anchor = document.createElement("a");
        let options_ : any = {
            body: JSON.stringify(params),
            observe: "response",
            responseType: "blob",
            headers: new HttpHeaders({
                "Content-Type": "application/json-patch+json",
            })
        };
        this.http.request("post", url, options_)
        .subscribe((response) => {
            if (response['status']!=200) {
                this.nzmessage.error('导出失败,请重试。');
                return;
            }
            const responseBlob =
            response instanceof HttpResponse ? response.body :(<any>response).error instanceof Blob ? (<any>response).error : undefined;
                        
            let objectUrl = window.URL.createObjectURL(responseBlob);
            anchor.href = objectUrl;
            anchor.download = (new Date()).getTime() + '.xls';
            anchor.click();
            window.URL.revokeObjectURL(objectUrl);
            
        });
       this.agGrid.api.hideOverlay();
    }
    //导出excel格式编辑
    gridapilist(group1:any) {
        let exportconfig: Array<ExportModel> = new Array<ExportModel>();
        for (let index = 0; index < group1.length; index++) {
            const el = group1[index];
            let colfig:ExportModel = new ExportModel();
            if (this.titleGroupName && (el.groupId == '0' || el.groupId == '1')) {
                switch (el.groupId) {
                    case '0':
                        colfig.title = this.titleGroupName.filter((e) => e.groupId == '0')[0].groupName;
                        break;
                    case '1':
                        colfig.title = this.titleGroupName.filter((e) => e.groupId == '1')[0].groupName;
                        break;
                    default:
                        break;
                }
                for (let j = 0; j < el.children.length; j++) {
                    const childs = el.children[j];
                    let col:ExportModel = new ExportModel();
                    col.title= childs.colDef.headerName;
                    if (childs.colDef.headerName=="操作") {
                      continue;
                    }
                    col.columnName = childs.colDef.field;
                    colfig.child.push(col);
                }
            } else {
                if (el.children) {
                    if (el.children[0].colDef.headerName=="操作") {
                      continue;
                    }
                    colfig.title = el.children[0].colDef.headerName;
                    colfig.columnName = el.children[0].colDef.field;
                } else {
                    if ( el.colDef.headerName=="操作") {
                      continue;
                    }
                    colfig.title = el.colDef.headerName;
                    colfig.columnName = el.colDef.field;
                }
            }
        
            exportconfig.push(colfig);
        }
        return exportconfig;
    }
   
    async refresh() {
        this.rowRefresh.emit();
    }

}


自定义列组件代码

html:

<div [@openClose]="isOpen ? 'open' : 'closed'" class="user-defined"
    (@openClose.start)="onAnimationStart($event)"
    (@openClose.done)="onAnimationDone($event)"
    (mousemove)="onMousemove($event)"
    (mouseup)="onMouseup($event)">
    <div class="linelist" [style.height]="listHeight+'px'">
        <div style="padding:18px;border-bottom: 1px solid #f4f4f4;">
            <label>自定义列 &nbsp;&nbsp;  <span class="text-smail">勾选需要显示的列,拖动列名进行排序。</span></label>
            <div class="btn-close">
                <i style="font-size: 18px;cursor:pointer;" nz-icon [type]="'close'" (click)="modalclosed()"></i>
            </div>
        </div>
        <div class="modalbody">
            <div *ngIf="leftColumnList" class="columnlist">
                <div *ngFor="let item of leftColumnList;index as i" class="line-he" [ngClass]="item.required?'linelist-req':''"
                        (mousedown)="onMousedown($event,item,i,'left-otherline')" (click)="hidecolumn(item)">
                    <label nz-checkbox [(ngModel)]="!item.hide" [nzDisabled]="item.required" style="vertical-align: top;margin-right: 4px;"></label>
                    <label [ngClass]="!item.hide?'text-bold':'text-smail'">
                        <span class="text-nowrap">{{item.colName}} </span>
                        <span nz-icon *ngIf="!item.required" class="icon-drag" [type]="'drag'"></span>
                    </label>
                    <label style="float: right;">
                        <span class="text-muted">宽度</span>  
                        <span style="width: 60px;display: inline-block;text-align: center;">{{item.width}}</span>px
                    </label>
                </div>
                <div class="line-other" id="left-otherline">
                    <label nz-checkbox [(ngModel)]="!otherRow.hide" style="vertical-align: top;margin-right: 4px;"></label>
                    <label [ngClass]="!otherRow.hide?'text-bold':'text-smail'">
                        <span class="text-nowrap">{{otherRow.colName}} </span>
                        <i nz-icon class="icon-drag-oh" [type]="'drag'"></i>
                    </label>
                    <label style="float: right;">
                        <span class="text-muted">宽度</span>  
                        <span style="width: 60px;display: inline-block;text-align: center;">{{otherRow.width}}</span>px
                    </label>
                </div>
            </div>
            <div *ngIf="centerColumnList"  class="columnlist">
                <div *ngFor="let item of centerColumnList;index as i" class="line-he"
                        (mousedown)="onMousedown($event,item,i,'center-otherline')" (click)="item.hide=item.hide==false">
                    <label nz-checkbox [(ngModel)]="!item.hide" [nzDisabled]="item.required" style="vertical-align: top;margin-right: 4px;"></label>
                    <label [ngClass]="!item.hide?'text-bold':'text-smail'">
                        <span class="text-nowrap">{{item.colName}} </span>
                        <span nz-icon class="icon-drag" [type]="'drag'"></span>
                    </label>
                    <label style="float: right;">
                        <span class="text-muted">宽度</span>  
                        <span style="width: 60px;display: inline-block;text-align: center;">{{item.width}}</span>px
                    </label>
                </div>
                <div class="line-other" id="center-otherline">
                    <label nz-checkbox [(ngModel)]="!otherRow.hide" style="vertical-align: top;margin-right: 4px;"></label>
                    <label [ngClass]="!otherRow.hide?'text-bold':'text-smail'">
                        <span class="text-nowrap">{{otherRow.colName}} </span>
                        <i nz-icon class="icon-drag-oh" [type]="'drag'"></i>
                    </label>
                    <label style="float: right;">
                        <span class="text-muted">宽度</span>  
                        <span style="width: 60px;display: inline-block;text-align: center;">{{otherRow.width}}</span>px
                    </label>
                </div>
            </div>
            <div *ngIf="rightColumnList"  class="columnlist">
                <div *ngFor="let item of rightColumnList;index as i" class="line-he"
                        (mousedown)="onMousedown($event,item,i,'right-otherline')" (click)="item.hide=item.hide==false">
                    <label nz-checkbox [(ngModel)]="!item.hide" style="vertical-align: top;margin-right: 4px;"></label>
                    <label [ngClass]="!item.hide?'text-bold':'text-smail'">
                        <span class="text-nowrap">{{item.colName}} </span>
                        <span nz-icon class="icon-drag" [type]="'drag'"></span>
                    </label>
                    <label style="float: right;">
                        <span class="text-muted">宽度</span>  
                        <span style="width: 60px;display: inline-block;text-align: center;">{{item.width}}</span>px
                    </label>
                </div>
                <div class="line-other" id="right-otherline">
                    <label nz-checkbox [(ngModel)]="!otherRow.hide" style="vertical-align: top;margin-right: 4px;"></label>
                    <label [ngClass]="!otherRow.hide?'text-bold':'text-smail'">
                        <span class="text-nowrap">{{otherRow.colName}} </span>
                        <i nz-icon class="icon-drag-oh" [type]="'drag'"></i>
                    </label>
                    <label style="float: right;">
                        <span class="text-muted">宽度</span>  
                        <span style="width: 60px;display: inline-block;text-align: center;">{{otherRow.width}}</span>px
                    </label>
                </div>
            </div>
            <div>
                <button nz-button nzType="primary" style="width:90px" (click)="savecolumn()">保存</button>
                <button nz-button nzType="default" style="width:90px" (click)="modalclosed()">关闭</button>
                <button nz-button nzType="default" style="width:90px" (click)="resetCloumn()">恢复默认</button>
            </div>
        </div>
    </div>
</div>

scss:


.user-defined{
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999; 
  width: 100%;
  height: 100%;
  background-color: rgba(00, 00, 00, 0.5);
  opacity: 0;
  .btn-close{
    float: right;
    text-align: center;
    color: rgba(0, 0, 0, 0.45);
    :hover{
      color: #444;
    }
  }
  .linelist{
    position: relative;
    border: 1px solid #f4f4f4;
    border-radius: 5px;
    width: 900px;
    overflow: hidden;
    margin: auto;
    margin-top: 100px;
    background: white;
  }  
  .modalbody{
    padding: 20px;
    overflow-y: auto;
    overflow-x: hidden; 
    height: calc(100% - 60px);
  }
  .modalbody::-webkit-scrollbar {
    width: 10px;
    height: 1px;
  }
  .modalbody::-webkit-scrollbar-thumb {
    background-color: rgba(0,0,0,.2);
    -webkit-background-clip: padding-box;
    background-clip: padding-box;
    border-radius: 10px;
    -webkit-box-shadow: inset 1px 1px 0 rgba(0,0,0,.1), inset 0 -1px 0 rgba(0,0,0,.07);
  }
  .modalbody::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
    border-radius: 10px;
    background: #EDEDED;
  }
  .linelist-req{
    background: #ececec !important;
  }
  .columnlist{
    border: 1px solid #f4f4f4;
    border-bottom: 0;
    position: relative;
    margin-bottom: 15px;
  }
  .line-he{
    line-height: 35px; 
    width: 100%;
    border-bottom: 1px solid #f4f4f4;
    padding: 0 10px;
    user-select: none;
    cursor:pointer;
    background: white;
    height: 35px;
  }
  .line-he:hover{
    background: #e9f2fb;
    .icon-drag{
      opacity: 1;
    }
  }
  
  .line-other{
    position: absolute;
    top: -500px;
    left: 120%;
    width: 860px;
    line-height: 35px;
    height: 35px;
    padding: 0 10px;
    border: 1px solid #f4f4f4;
    background: #e9f2fb;
    user-select: none;
    cursor:pointer;
  }
  .text-muted{
    color: #838a9d;
  }
  .text-smail{
    color: #b1b1b1;
  }
  .text-bold{
    font-weight: bold;
  }
  .text-nowrap{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: inline-block;
    max-width: 600px;
    cursor:pointer;
  }
  .icon-drag{
    opacity: 0;
    width: 20px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    position: relative;
    font-size: 20px;
    vertical-align: super;
    left: 3px;
    cursor:move;
  }
  .icon-drag-oh{
    width: 20px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    position: relative;
    font-size: 20px;
    vertical-align: super;
    left: 3px;
    cursor:move;
  }
}

ts:

import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { trigger, state, style, transition, animate } from '@angular/animations';



@Component({
  selector: 'app-user-defined-column',
  animations:[
    trigger('openClose', [
      // 组件模拟对话框的弹出动画
      state('open', style({
        opacity: 1,
      })),
      state('closed', style({
        opacity: 0,
      })),
      transition('open => closed', [
        animate('0.5s')
      ]),
      transition('closed => open', [
        animate('0.5s')
      ]),
      transition('* => *', [
        animate('0.5s')
      ]),
    ]),
  ],
  templateUrl: './user-defined-column.component.html',
  styleUrls: ['./user-defined-column.component.scss']
})
export class UserDefinedColumnComponent implements OnInit {

  
  @Input() definedColumn:any;
  @Input() dataColumnConfig:any;
  @Output() isUserDefined = new EventEmitter<any>();

  public listHeight: number= 0;
  public isOpen :boolean = false;
  public down:boolean = false;
  public mouseY:number = 0;
  public mouseX:number = 0;
  public oldTop:number = 0;
  public oldIndex:number = 0;
  public otherRow: any;
  public otherEl:any;
  public otherline:any;
  public columnStart = '';

  public leftColumnList:any;
  public centerColumnList:any;
  public rightColumnList:any;
  constructor() {
    this.otherRow ={
      aggFunc: null,
      colId: "operation",
      colName: "操作",
      flex: null,
      hide: false,
      pinned: "left",
      pivot: false,
      pivotIndex: null,
      rowGroup: false,
      rowGroupIndex: null,
      sort: null,
      sortIndex: null,
      width: 120
    };
    
    this.listHeight=document.documentElement.clientHeight-120;
  }

  ngOnInit() {
    if (!this.dataColumnConfig || this.dataColumnConfig.length<=0) {
      this.dataColumnConfig = [];
    } else {
      this.leftColumnList = this.dataColumnConfig.filter((item)=> item.pinned=="left");
      this.centerColumnList = this.dataColumnConfig.filter((item)=> !item.pinned);
      this.rightColumnList = this.dataColumnConfig.filter((item)=> item.pinned=="right");
    }
  }

  ngAfterViewInit(){
    setTimeout(()=>{
      this.isOpen = true;
    },100)
  }
  onAnimationStart(event:any){
    if (event.toState=="open") {
      event.element.style.display = "block";
    }
  }
  onAnimationDone(event:any){
    if (event.toState=="closed") {
      event.element.style.display = "none";
    }
  }

  resetCloumn(){
    let columnlist =[];
    this.definedColumn.map(item=>{
      const col = this.dataColumnConfig.filter(row=>{
        return row.colId == item.field;
      })
      if (col && col.length>0) {
        col[0]['colName'] = item.headerName;
        col[0].hide = false;
        columnlist.push(col[0])
      }
    });
    this.leftColumnList = columnlist.filter((item)=> item.pinned=="left");
    this.centerColumnList = columnlist.filter((item)=> !item.pinned);
    this.rightColumnList = columnlist.filter((item)=> item.pinned=="right");
    this.savecolumn();
  }

  hidecolumn(item){
    if (item.required) {
      return;
    }
    item.hide=item.hide==false;
  }

  savecolumn(){
    this.isOpen=false;
    this.dataColumnConfig = this.leftColumnList;
    this.dataColumnConfig = this.dataColumnConfig.concat(this.centerColumnList);
    this.dataColumnConfig = this.dataColumnConfig.concat(this.rightColumnList);
    setTimeout(()=>{
      this.isUserDefined.emit(this.dataColumnConfig);
    },400)
  }

  modalclosed(){
    this.isOpen=false;
    setTimeout(()=>{
      this.isUserDefined.emit();
    },400)
  }

  onMousedown(event: any,row,i,otherId:any) {
    if (row.colId == "operation") {
      return;
    }
    if (event.toElement.offsetTop || event.toElement.offsetTop == 0) {
      this.oldTop = event.toElement.offsetTop;
    } else if(event.target.parentElement.offsetTop) {
      this.oldTop = event.target.parentElement.offsetTop - 10;
    } else if(event.target.parentElement.parentElement.offsetTop) {
      this.oldTop = event.target.parentElement.parentElement.offsetTop - 10;
    } else {
      this.oldTop = i * 35;
    }
    switch (otherId) {
      case "left-otherline":
        this.columnStart="left";
        break;
      case "center-otherline":
        this.columnStart="center";
        break;
      case "riglt-otherline":
        this.columnStart="riglt";
        break;
    
      default:
        this.columnStart="";
        break;
    }
    for (let index = 0; index < event.path.length; index++) {
      const ement = event.path[index];
      if (ement.classList.contains('line-he')) {
        this.otherEl = ement;
        this.otherEl.style.background = "#ddd";
        break;
      }
    }
    this.otherline = window.document.getElementById(otherId);
    this.otherRow = row;
    this.mouseY = event.screenY;
    this.mouseX = event.screenX;
    this.down = true;
    this.oldIndex = i;
  };

  onMousemove(event: any) {
    if (this.down) {
      this.otherline.style.top = (this.oldTop + event.screenY - this.mouseY).toString() + 'px';
      this.otherline.style.left = (event.screenX - this.mouseX).toString() + 'px';
      let index = Number(((this.otherline.offsetTop)/35).toFixed(0));
      if (this.columnStart == "left") {
        if (this.oldIndex == index || index >= this.leftColumnList.length || index < 0) {
          return;
        }
        if (this.leftColumnList[index].colId == "operation") {
          return;
        }
        this.leftColumnList[this.oldIndex] = this.leftColumnList.splice(index, 1, this.leftColumnList[this.oldIndex])[0];
      } else if(this.columnStart == "center"){
        if (this.oldIndex == index || index >= this.centerColumnList.length || index < 0) {
          return;
        }
        this.centerColumnList[this.oldIndex] = this.centerColumnList.splice(index, 1, this.centerColumnList[this.oldIndex])[0];
      } else if (this.columnStart == "right") {
        if (this.oldIndex == index || index >= this.rightColumnList.length || index < 0) {
          return;
        }
        this.rightColumnList[this.oldIndex] = this.rightColumnList.splice(index, 1, this.rightColumnList[this.oldIndex])[0];
      } else {
        return;
      }
      this.oldIndex = index;
    }
  }

  onMouseup(event: any) {
    this.down = false;
    if (this.otherline) {
      this.otherline.style.top = "-500px";
      this.otherline.style.left = "120%";
    }
    if (!this.otherEl) {
      return;
    }
    this.otherEl.style.background = "#ffffff";
  }
}

使用:

/*html*/
    <ag-grid-single #agGridTable style="height: calc(100% - 160px);"
        [rowData]="dataTable" 
        [columnDefs]="columnDefs"
        (exportDataAsExcel)="export()"
        (rowRefresh)="refresh()"
    ></ag-grid-single>
/*列属性配置*/
this.columnDefs = [
            {
                field: 'operation', headerName: '操作',
                cellRenderer: 'buttonRenderer',
                cellRendererParams: {
                    label: ['受理', '处理结果', '无效投诉', '记录回访'],
                    onClick: [
                        this.acceptAdvice.bind(this),
                        this.deal.bind(this, operationEnum.result),
                        this.openInvalid.bind(this),
                        this.deal.bind(this, operationEnum.record)
                    ],
                    icon: ['soli.svg', 'cljg.svg', 'hfjl.svg', 'wxts.svg'],
                    filter: function(rowData) {
                        let btnList: Array<number> = [];
                        switch (rowData.status) {
                            case statusEnum.complete:
                                btnList.push(2);
                                btnList.push(3);
                                break;
                            case statusEnum.waiting:
                                btnList = [0, 1, 2, 3];
                                break;
                            case statusEnum.doing:
                                btnList = [0, 1, 2, 3];
                                break;
                            default:
                                break;
                        }
                        return btnList;
                    }
                },
                pinned: 'left', minWidth: '150', width: '150', suppressMovable: true,
                suppressColumnsToolPanel: true, sortable: false, resizable: false, headerClass: ['table-th-center'],
            },
            {field: 'name', headerName: '姓名', width: '100', pinned: 'left', suppressMovable: true,},
            {field: 'phoneNumber', headerName: '联系方式', },
            {field: 'idCardNo', headerName: '身份证号码', },
            {
                field: 'status_Name', headerName: '状态', 
                cellClass: function(params){
                    if (params.data.status == 1) {
                        return ['status-dian','status-dian-1']
                    }
                    if (params.data.status == 2) {
                        return ['status-dian','status-dian-2']
                    }
                    if (params.data.status == 3) {
                        return ['status-dian','status-dian-3']
                    }
                    if (params.data.status == 5) {
                        return ['status-dian','status-dian-5']
                    }
                    return 'status-dian';
                }
            },
            {field: 'content', headerName: '投诉建议内容', cellRenderer: "tooltipRenderer"},
            {field: 'fileList', headerName: '辅助信息', cellRenderer: "loadImgRenderer",},
            {field: 'typeId_Name', headerName: '问题类型' },
            {field: 'inCompany', headerName: '所在单位' },
            {field: 'creationTime', headerName: '投诉时间'},
            {field: 'processTime', headerName: '受理时间'},
            {field: 'deptName', headerName: '被投诉部门'},
            {field: 'finishedTime', headerName: '完成时间'},
            {field: 'processMan', headerName: '处理人'},
            {field: 'result', headerName: '处理结果', cellRenderer: "tooltipRenderer"},
            {field: 'operatorMan', headerName: '操作人'},
            {field: 'cancelTime', headerName: '取消时间'},
            {field: 'cancelReason', headerName: '取消原因', cellRenderer: "tooltipRenderer"},
            {field: 'returnVisit', headerName: '回访记录', cellRenderer: "tooltipRenderer"},
            {field: 'starCnt_Name', headerName: '结果评价', cellRenderer: "tooltipRenderer"},
        ];
    }
    

ag-grid列的渲染器agGrid-renderer

button-column


  <div style="text-align: center;width: 100%;">
    <span *ngFor="let item of label;index as i">
      <a *ngIf="!!icon && !!icon[i]; else elseBlock" (click)="invokeParentMethod($event,i)">
        <img class="td-imgbtn"
          [src]="'assets/icon/'+ icon[i]" 
          [alt]="item" 
          [title]="item"
        />
      </a>
      <ng-template #elseBlock>
        <a class="td-imgbtn"  [ngSwitch]="item">
          <span *ngSwitchCase="'编辑'"  (click)="invokeParentMethod($event,i)">
            <span *ngIf="isGranted_update()">
              <i class="anticon anticon-edit mr-sm"></i>
              <span>{{item}}</span>
            </span>
          </span>
          <span *ngSwitchCase="'修改'"  (click)="invokeParentMethod($event,i)">
            <span *ngIf="isGranted_update()">
              <i class="anticon anticon-edit mr-sm"></i>
              <span>{{item}}</span>
            </span>
          </span>
          <span *ngSwitchCase="'删除'">
            <span *ngIf="isGranted_delete()">
              <i class="anticon anticon-delete mr-sm"></i>
              <ng-container>
                <nz-popconfirm nzTitle="是否确定删除" (nzOnConfirm)="invokeParentMethod($event,i)" nzOkText="确定" nzCancelText="取消">
                  <a nz-popconfirm>
                    <span>{{item}}</span>
                  </a>
                </nz-popconfirm>
              </ng-container>
            </span>
          </span>
          <span *ngSwitchDefault  (click)="invokeParentMethod($event,i)">
            <span>{{item}}</span>
          </span>
        </a>
      </ng-template>
      <nz-divider nzType="vertical" *ngIf="label.length-1 != i"></nz-divider>
    </span>
  </div>
import { Component } from '@angular/core';
import { PermissionService } from '@shared/auth';
import { ICellRendererAngularComp } from 'ag-grid-angular';


@Component({
  selector: 'button-column',
  templateUrl: './button-column.component.html',
  styles: [
    `
      .td-imgbtn {
        height: 16px;
      }
    `,
  ],
})
export class ButtonColumnRenderer implements ICellRendererAngularComp {
  public params: any;
  public type: string = 'text';
  public label: Array<string> = [];
  public icon: Array<string> = [];
  public onClick: Array<any> = [];
  public filter: any;
  public permissions:any;
  
  
  constructor(private permission: PermissionService){

  }

  public btnList: Array<number> = [];
  agInit(params: any): void {
    this.params = params;
    this.permissions = params.permissions;
    this.type = this.params.type;
    this.filter = this.params.filter;
    let btns = this.params.label;
    let icons = this.params.icon;
    let clicks = this.params.onClick;
    if (this.filter && this.filter instanceof Function) {
      this.btnList = this.filter(this.params.node.data);
      if (this.btnList.length < btns.length) {
        for (let index = 0; index < this.btnList.length; index++) {
          const el = this.btnList[index];
          this.label.push(btns[el]);
          this.icon.push(icons[el]);
          this.onClick.push(clicks[el]);
        }
      } else {
        this.label = this.params.label;
        this.icon = this.params.icon;
        this.onClick = this.params.onClick;
      }
    } else {
      this.label = this.params.label;
      this.icon = this.params.icon;
      this.onClick = this.params.onClick;
    }
  }

  public invokeParentMethod($event, index) {
    if (this.onClick[index] instanceof Function) {
      // put anything into params u want pass into parents component
      const params = {
        event: $event,
        rowData: this.params.node.data
      }
      this.onClick[index](this.params.node.data);
    }
  }

  isGranted_delete():boolean{
    if (this.permissions) {
      if (this.permissions['delete']) {
        return this.permission.isGranted(this.permissions['delete']);
      }
    }
    return true;
  }

  isGranted_update(): boolean {
    if (this.permissions) {
      if (this.permissions['update']) {
        return this.permission.isGranted(this.permissions['update']);
      }
    }
    return true;
  }

  refresh(): boolean {
    return false;
  }
}

还有loadImg-column,tooltip-column 这两个渲染组件,用的是ZG-ZORRO的组件,代码就不帖出来了

你可能感兴趣的:(ag-grid,typescript,angular)