Search code examples
angularhref

How to fire function by clicking on text(not button) a href doesn't work


I have a line of text(dynamic). when the user clicks on it, it fires a function. It works when I don't use the a tag. The minute I add the a tag (I want it to look like a link, even if it isn't), when the user clicks on the text, it just goes to the homepage. Here are the two ways I've tried it:

              <mat-list-item><b class="title"><a href="#" onclick="downloadFile(batchList.dataPath)" class="dlLink" >Data Path:{{batchList.dataPath}}</a></b> 
//this just redirects to the homepage

<mat-list-item (click)="downloadFile(batchList.dataPath)"><b class="title">Data Path:{{batchList.dataPath}} </b>
//this works, as in the function is fired. But it doesn't act like a link, which I want. I've tried using stop propogation, by adding it to the end of my function, like so:

downloadFile(pathToDownload) {
    this.showLoader = true;
    console.log(pathToDownload);
    from(this.downloadFileService.downloadFile({'pathToDownload': pathToDownload}))
      .subscribe((data: any) => {
        saveAs(new Blob([data], {type: 'application/octet-stream'}), (pathToDownload.substring(pathToDownload.indexOf('part'))));
        this.showLoader = false;
        setTimeout(() => {
        }, 300000)
      })
    event.stopPropagation();
     }

//but it doesn't work. 

Any ideas?


Solution

  • It could be because you are using onClick when you should be using (click) instead. Please refer the below example.

    <a href="javascript:void(0);" (click)="downloadFile()" class="dlLink" >Data Path:{{batchList.dataPath}}</a>
    

    Stackblitz example