What is the best way to initiate a file download using Angular 2?

I am currently working on an application that allows users to browse and download phone call recordings.

One key feature of this application is a table that displays the recordings along with relevant information using *ngFor. Each row in the table includes a checkbox for selecting the recording for download. I have managed to log the links to the sample mp3 files, but I'm stuck on how to enable the actual downloading of these mp3s.

My goal is to achieve this functionality using Typescript without relying on jQuery.

<table>
        <thead>
            <tr>
                <th>
                    <input type="checkbox" [checked]="isAllChecked()" (change)="checkAll($event)"> </th>
                <th>Date</th>
                <th>Time</th>
                <th>Duration</th>
                <th>Calling Number</th>
                <th>Called Number</th>
                <th> </th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let entry of recordingsList">
                <td>
                    <input type="checkbox" [(ngModel)]="entry.isSelected"> </td>
                <td>{{entry.date}}</td>
                <td>{{entry.time}}</td>
                <td>{{entry.duration}}</td>
                <td>{{entry.callingNumber}}</td>
                <td>{{entry.calledNumber}}</td>
                <td>
                    <button (click)="openPlayer(entry)" class="play-button"><i class="material-icons">play_arrow</i></button>
                </td>
            </tr>
        </tbody>
    </table>

-

// Trigger download for selected recordings

    downloadSelected() {
        let isSelected = this.recordingsList.filter(x => x.isSelected);
        isSelected.forEach(x => console.log(x.audio));
    }

-

Your input and help on this matter would be greatly appreciated.

Answer №1

Providing a direct solution to the query, one option is to launch a new tab for each link:

downloadSelected() {
        let selectedItems = this.recordingsList.filter(item => item.isSelected);
        selectedItems.forEach(item => window.open(item.audio, '_blank'));
    }

However, this method may not offer the most user-friendly experience as it could result in multiple tabs opening simultaneously. Instead, my recommendation is to generate a custom URL (e.g. example.com/bulk-download?ids=1,34,56) that creates a zip file containing the chosen files and enables the user to conveniently download them from a single source.

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

having trouble retrieving information from mongodb

Currently working with nestjs and trying to retrieve data from a collection based on the 'name' value. However, the output I am getting looks like this: https://i.stack.imgur.com/q5Vow.png Here is the service code: async findByName(name):Promi ...

Using Async/Await for Timers within a Loop in Javascript

Currently developing a "Timeblocks" style application for university. The main concept involves having a list of subtasks, each with a specified time limit. The goal is to iterate through these tasks, utilizing a timer to countdown the allocated time and t ...

Determining block time based on block number within Polygon Mumbai Testnet

Is there a dependable method to identify the production time of a specific block in Polygon Mumbai Testnet using only its block number? I am unable to utilize an Api for this purpose and am seeking a more user-friendly computational solution. Any suggest ...

Error occurred while making a request to https://registry.npmjs.org/corepack. Failed due to connection issue: unable to reach the host

Previously, NPM was functioning without any issues, but now I am facing a problem where any attempt to connect to the registry results in a timeout. When using NPM, I receive an error message stating request to https://registry.npmjs.org/corepack failed, ...

Rendering on the server with React, React-Router, and Express

I'm currently in the process of setting up server-side rendering for my react application and I'm utilizing the fantastic react-router module to enable it to manage non-js scenarios (such as certain crawlers or users with javascript disabled). Ne ...

Is it possible to use the same HTML select/dropdown menu for multiple rows in a table?

I am working with an HTML table that usually has between 10-30 rows, each containing a column for "item name". The drop down menu consists of about 75 products to choose from. In order to reduce the page size, I want to use a single drop down list for all ...

Stop const expressions from being widened by type annotation

Is there a way to maintain a constant literal expression (with const assertion) while still enforcing type checking against a specific type to prevent missing or excess properties? In simpler terms, how can the type annotation be prevented from overriding ...

Can node.js be run on a server alongside another JavaScript file?

I have developed a small web application on my personal server. It consists of a few HTML, CSS, and JavaScript files. I am looking to incorporate Node.js with the following simple code: var mysql = require('mysql'); var fs = require('fs&apos ...

Displaying variables as HTML in Node.js involves rendering the variable data

Currently experimenting with displaying a Node.js variable as HTML. This is my setup in app.js using Express: Package.json "dependencies": { "body-parser": "~1.12.0", "cookie-parser": "~1.3.4", "debug": "~2.1.1", "express": "~4.12.2", ...

Updates cannot be flushed while React is currently rendering

My goal is to display an alert using sweetalert2 when an error is returned by the API. To achieve this, I check if the error message is not empty in my render method and trigger the alert for the user accordingly. Upon submitting the form, an API call is ...

Vue.js Applications tend to encounter Expected Errors originating from JavaScript

I've been diving into learning Vue.js using Visual Studio 2017. Currently, my goal is to create applications with multiple buttons that trigger the display of a message upon being clicked. However, when I attempt to run this code, I encounter the foll ...

The characteristics of property 'X' do not align

I have a challenge that I am currently working on. I am creating an addIdToAnimal function that will take any type of Animal and assign an id to it. Every animal object has an attribute called animalType, which is defined as an enum. My main inquiries ar ...

What is the best way to refresh a Load on Demand feature in Nativescript?

In my RadListView, the data displayed changes depending on the day selected by the user in a calendar. Currently, I am using loadOnDemandMode = "Manual" and it functions smoothly until all the available data is loaded. At that point, I trigger listView.no ...

Display a JavaScript variable as an attribute within an HTML tag

let disableFlag = ''; if(value.action.length === 0) { disableFlag = 'disabled="disabled"'; } row += '<td><input type="checkbox" name="create" value="1" class="checkbox" data-action="'+ value.action + '" data-co ...

Exploring the narrowing capabilities of TypeScript within while loops

When I write while loops, there are times when I know for sure that a certain value exists (connection in this case), but the control flow analysis is unable to narrow it down. Here's an illustration: removeVertex(vertex: string) { const c ...

Getting the text value from a table in JavaScript is a straightforward process. By using

I am working with a table displaying available hotel rooms and want to change the text color to green if the room is marked as "available." Is there a way to check the innerHTML of a td element to see if it contains the word "available"? var status = do ...

In TypeScript, encountering an unanticipated intersection

In my "models" registry, whenever I select a model and invoke a method on it, TypeScript anticipates an intersection of parameters across all registered models. To demonstrate this issue concisely, I've created a dummy method called "getName". expor ...

Best practices for making an AJAX call to fetch information from a database

I have a database containing a single table. The table includes columns for Company and Time, among others, with Company and Time being crucial. Users can make appointments by filling out a form. Within the form, there are 2 <select> elements - one ...

Display or conceal a div element depending on the value selected in Vue.js

I have a Vue.js dropdown and I would like to show or hide my div based on the selected value in the dropdown. The current code is only working for one ID, but I want it to work for all IDs. I want to toggle the visibility of my div based on the option&apos ...

Iterating through an array of objects and performing reduction based on various key-value pairs

I am faced with a challenge of consolidating a large array of objects into one single array that has a specific structure. Each item, such as a banana, needs to be present in two separate objects for buy orders and sell orders, each with their own distinct ...