1

I have a method that gets invoked based on certain user action. In that method I am trying to download a file using this approach.

But I don't want to use/refer document object directly so I am using combination of Renderer2 and ElementRef. This is snapshot of code:

const link = this.renderer.createElement('a');
this.renderer.setAttribute(link, 'download', requiredFile.name);
this.renderer.setAttribute(link, 'href', requiredFile.url);
this.renderer.setAttribute(link, 'target', '_blank');
this.renderer.appendChild(this.elementRef.nativeElement, link);
// how to achieve link.click() here?
this.renderer.removeChild(this.elementRef.nativeElement, link);

I need some help to figure out how to invoke DOM click() method here using Renderer2 and ElementRef

Aakash Goplani
  • 1,150
  • 1
  • 19
  • 36
  • Does this answer your question? [Opening PDF file in new tab angular 4?](https://stackoverflow.com/questions/51204276/opening-pdf-file-in-new-tab-angular-4) – mbojko Sep 13 '20 at 10:57
  • Why does link.click() not work here..? – MikeOne Sep 13 '20 at 11:29

1 Answers1

0

AFAIK there are two methods to register an event on a DOM element. The first one is with vanilla JavaScript and the second one with rxjs operators.

Method 1

fromEvent(link, 'click', () => console.log('do something here')).subscribe() // don't forget to unsubscribe

Method 2

link.addEventListener('click', () => console.log('clicked 2'))

I remember that it was discouraged to use the second method in combination with Render. This is not the case anymore though

Method 3

this.renderer.listen(this.elementRef.nativeElement, 'click', (event) => {
   console.log('Clicked')
})

Dispatch click event automatically

1)

const clickEvent = new Event('click')
this.elementRef.nativeElement.dispatchEvent(clickEvent)

Like @MikeOne wrote in the comments

link.click()
profanis
  • 2,741
  • 3
  • 39
  • 49
  • I think above two solution work when user manually click the element. I want click() to happen automatically. – Aakash Goplani Sep 13 '20 at 11:26
  • @KinleyChristian I updated my answer. It seems that it's not crystal clear what you are trying to achieve. The `link.click()` it does the trick. What is stopping you from using it? – profanis Sep 13 '20 at 11:58