Activate the download upon clicking in Angular 2

One situation is the following where an icon has a click event

    <md-list-item *ngFor="let history of exportHistory">
        <md-icon  (click)="onDownloadClick(history)" md-list-avatar>file_download</md-icon>
        <a md-line>{{history.exportDate_epoch | epoch | date:'mediumDate'}}</a>
        <p md-line> Exported by: {{history.by}}</p>
        <p md-line> {{history.numberOfEntries}} Entries</p>
    </md-list-item>

In this scenario, my history object includes a 'url' property with the download link.

When I use the function below, it retrieves the download link.

onDownloadClick(history: ExportHistoryModel) {
    console.log(history.url);
}

My objective is to simulate triggering the file download just like clicking on a regular link. Any suggestions?

Answer №1

The attributes of md-icon are not clear to me, but one way to use it is by enclosing it within an anchor tag:

<md-list-item *ngFor="let history of exportHistory">
    <a href="{{history.url}}"><md-icon  (click)="onDownloadClick(history)" md-list-avatar>file_download</md-icon></a>
    <a md-line>{{history.exportDate_epoch | epoch | date:'mediumDate'}}</a>
    <p md-line> Exported by: {{history.by}}</p>
    <p md-line> {{history.numberOfEntries}} Entries</p>
</md-list-item>

Answer №2

If you're looking to download files in JavaScript, there are various methods that can be used, as discussed in this informative blog post.

One of the most effective techniques involves dynamically generating an anchor tag with the "download" attribute in HTML5.

const url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/HTML5_logo_and_wordmark.svg/130px-HTML5_logo_and_wordmark.svg.png';
$('<a />')
  .attr('href',url)
  .attr('download', 'YourFileName.png')
  [0].click();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An issue arises following an upgrade in Angular from version 9 to version 10, where the property 'propertyName' is being utilized before it has been initialized

I've spent time looking on Google, Github, and Stackoverflow for a solution to this error, but I'm still struggling to fix it. Can anyone offer a suggestion or help? Recently, I upgraded my Angular project from version 9 to version 10, and after ...

What is the correct way to define the onClick event in a React component?

I have been encountering an issue while trying to implement an onClick event in React using tsx. The flexbox and button are being correctly displayed, but I am facing a problem with the onClick event in vscode. I have tried several ideas from the stack com ...

Upon selecting a checkbox, I desire for a corresponding checkbox to also be marked

I am looking to enhance my current project by incorporating a feature that allows the user to simply check a checkbox with specific content once. For example, I have a recipes page where users can select ingredients they need for each recipe while planning ...

Having trouble getting jQuery .append() to behave the way you want?

I have created a code snippet to display a table like this: $("#results").append("<table><tr><th>Name</th><th>Phone Number</th></tr>"); $("#results").append("<tr><td>John</td><td>123123123 ...

extracting array index from a Mongoose array

//index.js let countryNameList = { "name"=["Bangladesh","India","Australia"] } //Output Section let findCountryIndex = awaitDataModel.find({$indexOfArray:{CountryName:"Bangladesh"}}) console.log(findCountryIndex); //Expecting Output : 0 I am l ...

Warning: Attempting to modify a property that is not defined - 'action'

My code includes a datatable and an alert that pops out. The datatable functions properly with or without the alert, but the alert does not work well when combined with the datatable. Could this be causing a conflict in the code? An error message indicates ...

Akita and Angular Error Exploration: Analyzing the StaticInjector and NullInjector in the Context of Store and

I encountered an issue with the Akita state management implementation while working on an Angular project. Here is a brief solution to help others who may face the same problem. The documentation and examples provided by Akita do not offer a clear explana ...

Angular Pipe: Working with Data Structures in Angular With Nested Arrays and Objects

After struggling to customize answers for similar questions, I find myself in need of some assistance. My current challenge involves using an angular pipe to filter the following data structure: subjects = [ { name: "subject1", keywords:[& ...

Learn how to selectively hide the header from the root layout on a single page in Next.js version 14

I am currently working on an app using Next.js 14 and TypeScript. In my root layout, I have added a header and footer. However, on one of the pages I created, I need to hide the header and footer. import type { Metadata } from "next"; import { In ...

What could be causing my PUT and DELETE requests to return a 404 status code?

I have encountered a problem with my MEN back-end app. In the express client router, I declared PUT and DELETE requests but they are returning a status 404 not found error. However, the POST request is functioning correctly. Could this ...

Undefined variable when initializing with ng-init

As a newcomer to AngularJS (and JavaScript in general), I'm currently facing an issue that I could use some help with. Below is the HTML template I am using: <ion-view view-title="Playlists"> <ion-content> <ion-list> ...

A guide on invoking a Struts 2 action with a different parameter for each row in a jQuery DataTable

Currently, I am working on a JAVAEE project that involves the use of Struts 2 and jQuery DataTable. In this project, I need to add a link with each row in the DataTable that will call an action based on the row's ID. Below is the HTML code for this s ...

Executing Knex promises sequentially within a for loop

I have recently started to dive into Node and asynchronous coding, but I am struggling with a fundamental concept. I am trying to seed a database using knex, reading data from a CSV file and iterating through the rows in a for loop. In each iteration, I ne ...

Creating a custom Jquery function to generate a Div element instead of a Textbox in your web application

I need assistance with a jquery function that retrieves data from a JSON PHP MySQL setup. The retrieved results are currently displayed in textboxes. function showData(wine) { $('#Id').val(wine.id); $('#question').val(wine.question ...

Encountered an issue while attempting to integrate Nebular into my Angular application

As a newcomer to Angular, I decided to try installing Nebular using the command ng add @nebular/theme. However, I encountered an error in the process. Upon entering the command into my terminal, the following error message appeared: ? Which Nebular theme ...

What is the best way to pass the "getjson" capability from one function to another in a seamless manner?

Currently, I am dealing with a situation where a getjson call is used to retrieve a large amount of data. However, I find myself constantly having to check if the data is null or not. Here is an example: if (data.Height == "") { $(&ap ...

How can I make TypeScript's http.get Observable wait for the inline parameter to be returned?

I'm currently facing an issue with my http.get call in which I need one of the parameters (getUserToken) to be returned before the function is executed. However, I don't want to chain them together since the calling function getSomeData returns a ...

Understanding how to extract and utilize the display name of enums from a C# Web API within an Angular

Within my C# web API, I have established an enum with a designated display name: public enum Countries { Australia, [Display(Name="New Zealand")] NewZealand } To showcase this list in a dropdown menu within my Angular project, I transmit ...

AngularJS object array function parameter is not defined

Recently, I've been honing my AngularJS1x skills by following tutorials on Lynda and Udemy. One tutorial involved creating a multiple choice quiz. To test my understanding, I decided to modify the code and transform it into a fill-in-the-blank quiz. ...

AJAX request lacks the 'access-control-allow-origin' header

I'm currently integrating a weather API into my app to display real-time weather information. Although I've used this API before, I am now attempting to fetch the data asynchronously using AJAX to avoid full page reloads. Below is the JavaScrip ...