我有许多通过 *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));
关于javascript - Angular2 - 从窗口点击检测实体点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43309331/