Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

232
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!