如何在作为参数传入的validateResize函数中获取Angular组件实例?
问题原因
你将类普通方法作为回调函数传入第三方库时,方法会丢失原执行上下文,被调用时this指向库内部的调用方实例,自然无法访问当前组件的属性和方法。
解决方案
你可以选择以下任意一种方式修复this指向:
- 方案1:将validate方法定义为箭头函数(最常用)
箭头函数的this继承自定义时的外层上下文,不会被调用方修改:
@Component({ // 配置项 }) export class TdeComponent { // 其他业务代码 // 改成箭头函数定义 validate = (event: ResizeEvent): boolean => { if (event.rectangle.width < 50 || event.rectangle.height < 50) return false; // 此处this直接指向当前组件实例 console.log(this.你的组件变量) return true; } }
- 方案2:模板绑定时手动绑定this
无需修改方法定义,在传入参数时用bind方法固定this指向当前组件:
<div mwlResizable [enableGhostResize]="true" [validateResize]="validate.bind(this)" <!-- 其他配置 --> ></div>
注意:该方式每次变更检测都会生成新的函数实例,高频变更场景会有轻微性能损耗。
- 方案3:构造函数内提前绑定this
在组件初始化时就把方法的this固定为组件实例,原方法定义和模板绑定都不用修改:
@Component({ // 配置项 }) export class TdeComponent { constructor() { // 提前绑定this this.validate = this.validate.bind(this); } // 其他业务代码 validate(event: ResizeEvent): boolean { if (event.rectangle.width < 50 || event.rectangle.height < 50) return false; // 此处this指向当前组件实例 return true; } }
内容的提问来源于stack exchange,提问作者M. Akar
相关产品推荐
相关产品推荐

