Angular-Material表格中添加input框并检查整数的方法

283 阅读1分钟

一个功能需要在子SKU表格(行数随机)编辑对应的裁剪数量,并需要验证是否为正整数。 HTML代码如下:

<table mat-table [dataSource]="skuData" class="sku_table">
    <ng-container matColumnDef="print">
        <mat-header-cell *matHeaderCellDef> 商品ID </mat-header-cell>>
        <mat-cell *matCellDef="let row"> {{row.products_id}} </mat-cell>>
    </ng-container>
    ……
    <ng-container matColumnDef="order_qty">
        <mat-header-cell *matHeaderCellDef> 裁剪数量 </mat-header-cell>>
        <mat-cell *matCellDef="let row">
            <input type="number" min="0" step="1" [(ngModel)]="row.order_qty" 
            ngModelOptions]="{standalone: true}" value="{{row.order_qty}}" (change)="verifyQty()"
            ngDefaultControl>
        </mat-cell>
    </ng-container>
    <ng-container matColumnDef="back_qty">
        <mat-header-cell *matHeaderCellDef> 已回货数量 </mat-header-cell>>
        <mat-cell *matCellDef="let row"> {{row.back_qty}} </mat-cell>>
    </ng-container>
    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>>
</table>

其中(change)="verifyQty()"用于用户输入数字后失去焦点,对数字进行检查判断。
检查函数代码如下:

// 更新数量
  updateQty(): string[] {
    // 裁剪
    let tempOrderQty = 0;
    const tipsData: string[] = [];

    this.skuData.forEach(((value, index, array) => {
      if (this.general.isPositiveInteger(value['order_qty'])) {
        tempOrderQty = tempOrderQty + toInteger(value['order_qty']);
      }
      else {
        tipsData.push(value['products_sku'] + ' 裁剪数量不是正整数,已经帮你重置为0。');
        this.skuData[index].order_qty = 0;
      }
    }));

    // 重新统计总数
    this.orderData['order_qty'] = tempOrderQty;
    return tipsData;
  }

  // 验证数量弹窗
  verifyQty(): void {
    const tips = this.updateQty();

    if (tips.length > 0) {
      const alertTitleText = '提醒';
      const alertLabelText = '';
      const alertData: DialogData = {
        alertTitle: alertTitleText,
        alertLabel: alertLabelText,
        tips: tips,
      };
      this.openDialogNum(alertData);
    }
  }
  
  openDialogNum(alertData: DialogData): void {
    const alertDialogRef = this._matDialog.open(AlertDialogComponent, {
      width: '400px',
      height: 'auto',
      data: alertData,
    });
  }
  
  // 判断正整数,包含0
    public isPositiveInteger(value): boolean {
        const reg = /^[0-9]\d*$/;
        return reg.test(value);
    }

思路很简单:

  1. 存放数字的数组
  2. 如果有数字为0或不为正整数,往弹窗中添加一条数字对应的SKU用于提醒,并将数字重置为0
  3. 失去焦点后,打开弹窗并显示错误的SKU