Angular(ag-grid)中点击删除按钮触发TypeError: this.deleteContact is not a function错误的解决方法
解决AG-Grid按钮点击时
this.deleteContact is not a function错误 这个问题我之前也碰到过,核心原因是函数的this上下文丢失了:当你把this.onBtnClick1作为回调传给AG-Grid的cellRendererParams时,这个函数的this不再指向DashboardComponent的实例,而是绑定到了AG-Grid的组件上下文,自然找不到你定义的deleteContact方法。下面给你几个靠谱的解决办法:
方案1:用箭头函数定义回调函数
箭头函数会自动捕获外层作用域的this,是最简洁的解决方式:
// 修改onBtnClick1的定义为箭头函数 onBtnClick1 = (e) => { alert(e.data.id) this.deleteContact(e.data.id) }
方案2:在构造函数中手动绑定this
通过bind方法把函数的this强制绑定到组件实例,这也是Angular项目里常用的上下文保留手段:
constructor(private api: ApiService) { // 绑定this到当前组件实例 this.onBtnClick1 = this.onBtnClick1.bind(this); } // 原函数定义保持不变 onBtnClick1(e) { alert(e.data.id) this.deleteContact(e.data.id) }
方案3:传递回调时用箭头函数包裹
如果不想修改原函数的定义,可以在cellRendererParams里直接用箭头函数包裹回调,同样能保留组件的this:
columnDefs=[ {headerName: 'ID', field:'id', width: 200}, { headerName: 'Delete', cellRendererFramework: ButtonrendererComponent, cellRendererParams: { label: 'Delete', // 用箭头函数包裹,保留组件上下文 onClick: (e) => this.onBtnClick1(e) } }, ]
完整修改后的代码示例(方案1)
import { ButtonrendererComponent } from '../buttonrenderer/buttonrenderer.component'; export class DashboardComponent implements OnInit { frameworkComponents = { buttonRenderer: ButtonrendererComponent, } constructor(private api: ApiService) {} ngOnInit(): void { this.getContactDetails(); } columnDefs=[ {headerName: 'ID', field:'id', width: 200}, { headerName: 'Delete', cellRendererFramework: ButtonrendererComponent, cellRendererParams: { label: 'Delete', onClick: this.onBtnClick1 } }, ] deleteContact(id){ this.api.deleteContact(id) .subscribe(res =>{ alert("Contact deleted"); this.getContactDetails(); }); } // 箭头函数定义,自动保留组件上下文 onBtnClick1 = (e) => { alert(e.data.id) this.deleteContact(e.data.id) } }
内容的提问来源于stack exchange,提问作者 Daoudi Yassine
相关产品推荐
相关产品推荐

