You need to enable JavaScript to run this app. Angular动态创建DevExpress Grid组件时onClick渲染触发及属性可选问题
优惠活动
大模型
产品
解决方案
定价
更多

Angular动态创建DevExpress Grid组件时onClick渲染触发及属性可选问题

问题1:按钮onClick事件渲染阶段触发的原因与解决方案

原因

你在模板中写的[onClick]="click($event,b)"属于函数调用表达式,Angular在每次变更检测执行模板渲染时,都会直接执行这个表达式拿到返回值赋值给onClick输入属性,所以行渲染阶段事件就会被触发。而DevExpress的dxi-button的onClick输入属性要求接收的是函数引用,不是函数执行的返回结果。

解决方案

修改网格组件的ts代码,把click方法改成返回闭包函数的形式,模板只传入按钮参数,返回的函数会在点击时才执行:

网格组件ts代码修改

// 把原来的click方法替换成这个
click(button: any) {
  return (e: any) => {
    // e是DevExpress原生点击事件,包含当前行数据等信息
    this.parentMethod.emit(button.parentClassObject(e));
  }
}

网格组件模板修改

<dxi-button *ngFor="let b of col.buttons"
            [text]="b.text"
            [hint]="b.hint"
            [cssClass]="b.cssClass"
            [icon]="b.icon"
            [onClick]="click(b)"
>
</dxi-button>

问题2:属性可选添加的实现方案

原因

你用[type]="value ? '' : null"的方式不生效,是因为DevExpress组件的type输入属性会接收null/空字符串作为合法值处理,不会自动忽略该属性;且直接用插值type="{{col.type}}"在col.type不存在时会绑定为undefined,DevExpress也不会主动移除该属性,会导致列渲染异常。

解决方案

用*ngIf拆分两种列的渲染逻辑,有type属性的列才绑定type输入,没有的则不绑定该属性:

网格组件模板修改

<!-- 普通列,不绑定type属性 -->
<ng-container *ngFor="let col of columns">
  <dxi-column *ngIf="!col.type"
              [dataField]="col.dataField"
              [caption]="col.caption"
              [dataType]="col.dataType">
  </dxi-column>
  <!-- 按钮列,绑定type属性 + 渲染按钮 -->
  <dxi-column *ngIf="col.type"
              [dataField]="col.dataField"
              [caption]="col.caption"
              [dataType]="col.dataType"
              [type]="col.type">
      <dxi-button *ngFor="let b of col.buttons"
                  [text]="b.text"
                  [hint]="b.hint"
                  [cssClass]="b.cssClass"
                  [icon]="b.icon"
                  [onClick]="click(b)"
      >
      </dxi-button>
  </dxi-column>
</ng-container>

另外建议所有DevExpress组件的输入属性都统一用方括号[]绑定,不要用插值{{}},避免类型转换导致的异常。

内容的提问来源于stack exchange,提问作者nonoandy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 17:21:00