How to use DOM click() in Angular using Renderer2

1.7k views Asked by At

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

1

There are 1 answers

2
profanis On

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()