首页 > 解决方案 > 在单元格值更改之前验证?

问题描述

我有这个网格选项:

gridOptions: GridOptions = {
    suppressFieldDotNotation: true,
    paginationAutoPageSize: false,
    paginationPageSize: 10,
    domLayout: 'autoHeight',
    rowMultiSelectWithClick: false,
    rowSelection: 'multiple',
    onFilterChanged: (event) => this.onFilterChanged(event),
    onCellValueChanged: (event) => this.onCellValueChanged(event)
  } as GridOptions;

在单元格值上,我有这个:

  onCellValueChanged(event) {

    if (typeof event.newValue === 'string') {
      this.toastrService.error(event.newValue + ' is not a number!');
      return;
    }
}

只有一列是可编辑的,我想要的是用户输入一些不是数字或十进制的值,例如(1、1.1、1,1),我将该列设置为零,并显示消息。

我试过这样,但它显示十进制值 1.1 和 1,2(带点和逗号)的验证消息,另一个问题是如果验证为假,我不知道如何将该行上的列设置为零。

有什么建议吗?

标签: angularag-gridag-grid-angular

解决方案


不幸的是,没有直接的配置属性可以做到这一点。

我们必须创建一个新的单元格编辑器组件并将其注册到 columnDefs 中的列。

像这样:在这个例子中,我们可以通过三种方式来操作数据。

  1. 在这里,首先,由于输入类型是数字,因此只允许输入数字。

  2. 如果您不想这样做,请检查输入值是否为数字。如果不是,则分配零。

  3. 第三,如果值不正确,请勿编辑。

    import {
     AfterViewInit,
     Component,
     ViewChild,
     ViewContainerRef,
     } from '@angular/core';
     import { AgEditorComponent } from 'ag-grid-angular';
    
     @Component({
     selector: 'editor-cell',
     template: `<input
       type="number"  #########check1
       [(ngModel)]="value"
       #input
       style="width: 100%"
     />`,
     })
     export class PercentageCellEditor implements AgEditorComponent, AfterViewInit {
     private params: any;
     public value: number;
    
     @ViewChild('input', { read: ViewContainerRef })
     public input: ViewContainerRef;
    
     ngAfterViewInit() {
         // focus on the input
         setTimeout(() => this.input.element.nativeElement.focus());
     }
    
     agInit(params: any): void {
         this.params = params;
     }
    
     /* Component Editor Lifecycle methods */
     // the final value to send to the grid, on completion of editing
     getValue() {
         // check2
         this.value = !Number.isNaN(parseFloat(this.params.value)) ? parseFloat(this.params.value) : 0;
         return this.value;
     }
    
     // Gets called once before editing starts, to give editor a chance to
     // cancel the editing before it even starts.
     isCancelBeforeStart() {
         return false;
     }
    
     // Gets called once when editing is finished (eg if enter is pressed).
     // If you return true, then the result of the edit will be ignored.
     isCancelAfterEnd() {
         // check3
         return (this.value < 0 || this.value >= 100);
     }
     }
    

零件:

在grid的frameworkComponents中注册。

this.frameworkComponents = {
        percentageEditor: PercentageCellEditor
    }

将其添加到 columnDefs:

           {
                headerName: "Column Name",
                field: "columnFieldName",
                editable: true,
                cellEditor: "percentageEditor",
            }

推荐阅读