繁体   English   中英

Angular:在@HostListener 中传递一个 object

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

我使用 @HostListener 来管理我的事件,而不是(contextmenu)="myFunction(myFile)"

但我不知道如何在我的 *ngFor 循环中传递对象:

文件. file.component.html

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

file.component.ts

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

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

控制台日志显示“[Object Object]”,但我想完全按照(上下文菜单)的方式获取我的 object ...

谢谢 !

您的问题在于 DOM 元素中的属性道具被保存为字符串。 因此,当您将文件添加为属性时,实际发生了什么,您添加了它的字符串值,即 [Object Object]。

解决方案是在每个文件中保存索引值 (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