gpt4 book ai didi

javascript - Angular 2 和 typescript : Cannot access class instance from event handler

转载 作者:太空狗 更新时间:2023-10-29 18:21:31 27 4
gpt4 key购买 nike

我的用例要求我以编程方式将子组件的多个副本添加到模板(想想:使用 *ngFor="let childComponent of componentArray" 遍历数组)。子组件都发出一个 select 事件;不同之处在于,这些组件中的每一个在父组件中都有不同的事件处理程序。为了聪明,我决定将事件处理程序存储为 componentArray 的每个成员的属性。所以我的模板现在是这样的:

<my-cmp *ngFor="let childComponent of componentArray" (select)="childComponent.callback()"></my-cmp>

我的模型包含:

componentArray = [{data:0, callback:this.onSelect0}, {data:1, callback:this.onSelect1}];

onSelect0(){/*do stuff specific to childComponent 0*/}
onSelect1(){/*do stuff specific to childComponent 1*/}

callback 是对我希望触发特定 childComponent 的 select 事件的类方法的引用。 回调被正确触发;问题是我无法从它访问我的组件的其余部分,因为该上下文中的 this 在循环的迭代期间引用 component

这听起来比实际更令人困惑。我找到了一个解决方法,但它看起来真的很笨拙(我将类实例作为属性存储在 componentArray 的每个成员中)。我做了一个可以从 http://plnkr.co/edit/VxxCR8hjUsxQ3SABWe8E?p=preview 访问的 plunkr .基本上我的问题是:如果我将事件处理程序作为对象属性(上面的 childComponent.callback)传递,我如何访问我的类实例?欢迎任何反馈。

最佳答案

如果你直接传递一个方法引用,这是默认的 JS/TS 行为。您可以使用像 methodName.bind(this) 这样的 bind 或像 () => methodName() 这样的粗箭头函数来保留作用域

在您的 Plunker 中只需更改此行

  private thing = {name:'ThingOne', onSelect: this.handlerOne };

  private thing = {name:'ThingOne', onSelect:() => this.handlerOne() };

Plunker example

关于javascript - Angular 2 和 typescript : Cannot access class instance from event handler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37351113/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com