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

2
  • Does this answer your question? Opening PDF file in new tab angular 4? Commented Sep 13, 2020 at 10:57
  • Why does link.click() not work here..? Commented Sep 13, 2020 at 11:29

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

2 Comments

I think above two solution work when user manually click the element. I want click() to happen automatically.
@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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.