Search code examples
javascriptangularanchorcreateelement

Invoke a API call directing to success or failure with anchor tag created using java script


I have a button to behave it to be an anchor tag or link.Added below code when clicked on button.

download() {
        let link = document.createElement('a');
        document.body.appendChild(link);
        //link.href = this.downloadFile; // can i call a function here which has API invoking?
        link.onclick = this.downloadFile;
        link.click();
}
downloadFile() { 
        this.Service.download(
            id
        ).subscribe((data: any) => {
        },
        (error: any) => {

        });
    }

How can i call this function with anchor tag created?


Solution

  • Instead of using link.onclick, use the addEventListener method on your link to register your download method :

        function download() {
    
          var link = document.createElement('a'); 
          document.body.appendChild(link);
    
          link.addEventListener('click', this.downloadFile);
          link.click();
        }
    
        function downloadFile() { 
            console.log("Here we go");
        }
    

    BUT be carreful because if your method downloadFile is a class method, the "this" in the downloadFile function will be undefined or equal to window global object, and you will have to hard bind the this context using link.addEventListener('click', this.downloadFile.bind(this));