Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

233
Vistas
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 !

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda