Angular2 - 从窗口点击检测实体点击?

时间:2017-04-09 16:50:17

标签: javascript angular typescript

我通过*ngFor创建了很多项目:

 <my-item *ngFor="let item of myArray" [p]="item" > </my-item>

我可以通过

收听click事件
 <my-item ... (click)="doWork(item) > </my-item>

但是我不想附加这么多的事件处理程序(因为ngFor上有很多组件)。

我想知道是否可以将事件处理程序附加到window对象(仅一次)(通过@HostListener),然后分析target event属性并获得点击的实际Entity - 但我没有成功。

问题:

已经收听window click

I've made this plunker  但是,如何获得所点击的item*ngFor="let item of myArray")的实际参考?

换句话说:

export class App {
  myArray:Person[] = new Array<Person>();

  @HostListener("window:click", ['$event'])
   onWindowclick() {
   console.log('click') 
   // how can I get a reference to the currently clicked item (as a `Person` entity) ?

  }

Nb我不想附加ID,然后在数组中搜索该ID

2 个答案:

答案 0 :(得分:1)

使用自定义指令处理它,如下所示

import { Directive, HostListener, Renderer, ElementRef } from '@angular/core';
@Directive({
    selector: '[cicked]'
})
export class ClickDirective{

    constructor(
        private renderer: Renderer,
        private el: ElementRef
    ){}

    @HostListener('click') onClick() {
      this.el.nativeElement.attributes[..] // using this you handle handle the entity clicked
     console.log('some thing key upped')

    }
}

将此行用于指令中的必需参数,该指令在演示

中更新
console.log(JSON.stringify(this.el.nativeElement.attributes['ng-reflect-p'].nodeValue));

<强> LIVE DEMO

答案 1 :(得分:0)

我正在玩你的Plunkr,老实说,我认为这不可能(或打算在Angular2中)。

我认为可以使用的一些hacky解决方案:

添加display:none输入文本作为my-item中的子元素,其[value]绑定设置为p:Person

这显然不起作用,[value]绑定可以only be string

与上述相同,但使用&lt; \ select&gt;在第一个选项上标记[ngValue]绑定 此方法将保留完整的Person对象,但angular不会将value属性公开给DOM,因此无法从Window事件访问它。

现在,我犹豫不决说它不可能 - 因为我不是专家,但我建议只是坚持不管事件处理程序。

为数组中的每个项添加事件处理程序的开销很小。