DEV Community

venkateshpensalwar
venkateshpensalwar

Posted on

Use <a> Tag inside typeScript File

In an HTML document, the document.createElement() is a method used to create the HTML element.

Sometimes we get into situations where we want to use "a" Tag in HTML but we implemented their button previously and now we want to have "a" tag-like behavior in such cases "href" attribute will not be able to be used directly in the button html so in such cases within we can do 2 things

  1. change the "button" tag to "a" tag and use.
  2. use some kind of programmatic way to achieve the same behavior.

So 1st way of doing everyone knows we will get on 2nd way
we have the document.createElement() method provided by HTML and the same method we can have in typescript as nowadays most of the frameworks use typescript.

I have the following code which will show you how we can achieve this

<button (click)="downloadResume()"> Download Resume</button>
Enter fullscreen mode Exit fullscreen mode
downloadResume() {
  getResumeDownload()
}

async getResumeDownload() {
    try {
      const resumeURL = await getDownloadURL(
        ref(this.fireStorage, 'venkatesh_Resume.pdf')
      );
      if (resumeURL) {
        const a = document.createElement('a');
        a.href = resumeURL;
        a.click();
      }
    } catch (error) {
      this.snackbar.open('resumne Faild to Download', undefined, {
        duration: 2000,
      });
    }
  }

Enter fullscreen mode Exit fullscreen mode

here you can see I wrote one code to get the resume link from the Firebase storege and download it in a single go so on clicking the button I made a call and after receiving the resume URL I created an element and attached the download URL on "a" tag and clicked on it so it will download that file otherwise we will have to attach this URL to hidden tag and need to trigger someway.

So In this way, a simple trick will save your time, if you like this small tip then thank you and if you have any questions please let me know.


Top comments (0)