代码之家  ›  专栏  ›  技术社区  ›  BeetleJuice

Angular 2类型脚本(&T):无法从事件处理程序访问类实例

  •  6
  • BeetleJuice  · 技术社区  · 9 年前

    我的用例要求我以编程方式将一个子组件的多个副本添加到模板中(想想:使用 *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的类方法的引用 选择 要触发的事件。 回调 正确触发;问题是,我无法从中访问组件的其余部分,因为 this 在这种情况下,指的是 component 在循环的迭代过程中。

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

    1 回复  |  直到 9 年前
        1
  •  6
  •   Günter Zöchbauer    9 年前

    如果直接传递方法引用,这就是默认的JS/TS行为。您可以使用 bind 喜欢 methodName.bind(this) 或者像这样的胖箭头功能 () => methodName() 以保留此范围。

    在您的Plunker中,只需更改此行

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

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

    Plunker example