Uso @HostListener para administrar mis eventos en lugar de (contextmenu)="myFunction(myFile)"
Pero no sé cómo pasar objetos en mi bucle *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")); }El registro de la consola muestra "[Objeto de objeto]", pero quiero obtener mi objeto exactamente como lo haría (menú contextual) ...
Gracias !
Su problema radica en el hecho de que los accesorios de atributos en los elementos DOM se guardan como cadenas. Entonces, ¿qué sucede realmente cuando agrega su archivo como un atributo? Agrega su valor de cadena, que es [Objeto Objeto].
La solución sería guardar el valor del índice (component.html) en cada archivo y en el script (component.ts) hacer ajustes para que obtenga el índice del objeto del archivo del menú contextual. Después de eso, simplemente puede llamar al objeto de archivo por su índice en la matriz de archivos.
@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>