简体   繁体   English

Angular:在@HostListener 中传递一个 object

[英]Angular : Pass an object in a @HostListener

I use a @HostListener to manage my events instead of (contextmenu)="myFunction(myFile)"我使用 @HostListener 来管理我的事件,而不是(contextmenu)="myFunction(myFile)"

But I don't know how to pass objects in my *ngFor loop:但我不知道如何在我的 *ngFor 循环中传递对象:

file.component.html :文件. file.component.html

<div *ngFor="let file of fileList" >
  <div [attr.myFile]="file">{{ file.name }}</div>
</div>

file.component.ts : file.component.ts

@Input() fileList: MyFileList[] = [];

@HostListener('contextmenu', ['$event'])
onContextMenu(event: MouseEvent) {
  const targetElem: HTMLElement = (<HTMLElement>event.target);
  console.log(targetElem.getAttribute("myFile"));
}

The console log shows "[Object Object]" but i want to get my object exactly as (contextmenu) would...控制台日志显示“[Object Object]”,但我想完全按照(上下文菜单)的方式获取我的 object ...

Thanks !谢谢 !

Your problem lies in the fact that attribute props in DOM elements are saved as strings.您的问题在于 DOM 元素中的属性道具被保存为字符串。 So whats actually happening when you add your file as an attribute you add its string value which is [Object Object].因此,当您将文件添加为属性时,实际发生了什么,您添加了它的字符串值,即 [Object Object]。

The solution would be to save the index value (component.html) at each file and in script (component.ts) make adjustments so it gets the index of contextmenu file object. After that you can simply call the file object by its index in the file array.解决方案是在每个文件中保存索引值 (component.html),并在脚本 (component.ts) 中进行调整,以便它获得上下文菜单文件 object 的索引。之后,您只需通过其索引调用文件 object文件数组。

 @Input() fileList: MyFileList[] = []; @HostListener('contextmenu', ['$event']) onContextMenu(event: MouseEvent) { const targetElem: HTMLElement = (<HTMLElement>event.target); const indexAttr: any = targetElem.getAttribute("index"); // Since we are listening for a global contextmenu event // listener, we should check if the event target has // an index attribute if (:isNaN(indexAttr)) { const index; number = Number(indexAttr). const file = this;fileList[index]. console;log(file); } }
 <;-- Modify this div declaration so it holds a record of the index --> <div *ngFor="let file of fileList. let i = index"> <.-- Remember the value of the index in the element --> <div [attr.index]="i">{{ file.name }}</div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM