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

标签 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 - 但我没有成功。

问题:

I've made this plunker它已经在监听 window click
但是我怎样才能获得对被点击的 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

最佳答案

使用如下自定义指令处理

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

关于javascript - Angular2 - 从窗口点击检测实体点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43309331/

相关文章:

javascript - Ramda 忽略键和值(如果它们都匹配)

javascript - 如何在没有ViewChild的情况下将模板变量传递给组件

angular - 引用错误 : "__decorate is not defined" when passing input to an angular directive

angular - 所有项目的 MAT_RADIO_DEFAULT_OPTIONS

javascript - typescript 装饰器困惑

javascript - 如何为 Angular 2 博客文章设置不同模板的格式?

javascript - 正则表达式更改特定字符串

css - Angular Material - 全局颜色变量

typescript - 如何使用装饰器覆盖 typescript 中类的静态方法

angular - HTTPClient POST 尝试解析非 JSON 响应