简体   繁体   中英

Angular : Pass an object in a @HostListener

I use a @HostListener to manage my events instead of (contextmenu)="myFunction(myFile)"

But I don't know how to pass objects in my *ngFor loop:

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"));
}

The console log shows "[Object Object]" but i want to get my object exactly as (contextmenu) would...

Thanks !

Your problem lies in the fact that attribute props in DOM elements are saved as strings. So whats actually happening when you add your file as an attribute you add its string value which is [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.

 @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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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