Using Angular to Generate a File from Form Input and Delivering it to the User

I am attempting to develop a feature in Angular 9 that takes user input from a textarea, processes it, and then presents it back to the user as a downloadable (txt) file.

The structure of the form in app.component.html is as follows:

<form (ngSubmit)="onSubmit()" #myForm="ngForm">
  <textarea name="myText" ngModel></textarea>
  <input name="fileName" ngModel>
  <button type="submit">Download</button>
</form>

In my app.component.ts file, the code appears like this:

import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild('myForm', {static: true}) myForm: NgForm;

  onSubmit(){
    // process this.myForm.value.myText
    // serve file with this.myForm.value.fileName and myTextProcessed
  }
}

Is there a way for me to generate a file using Angular based on the data entered by the user in the form and present it for download?

Answer №1

To save a file without prompting for location, simply include the following function in your TypeScript file and call it from the submit action:

download() {
    let file = new Blob([this.myForm.form.value.myText], {type: '.txt'});
    let a = document.createElement("a"),
            url = URL.createObjectURL(file);
    a.href = url;
    a.download = this.myForm.form.value.fileName;
    document.body.appendChild(a);
    a.click();
    setTimeout(function() {
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);  
    }, 0); 
}

Check out this Stackblitz example for reference: https://stackblitz.com/edit/angular-bpbexb

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 getting a basic file upload to work in Angular2+? Wondering what the easiest method is to make it function properly? Look no

I successfully created a MEAN stack CRUD board using Angular 2+, Node.js, Express, and MongoDB. However, I encountered an issue when trying to add an upload function. The error message displayed was: compiler.js:486 Uncaught Error: Template parse errors: ...

"Exploring the New Feature of Angular 17: Named Router Outlets Implemented

One issue I am facing with my application is the rendering of different pages based on whether a user is logged in or not. The generic pages like the landing or logout page should be displayed within the primary router-outlet when the user is not logged in ...

Can TestCafe be used to simulate pressing the key combination (Ctrl + +)?

I've been having a tough time trying to use the key combination specified in the title (Ctrl + +). So far, this is what I've attempted: 'ctrl+\+' 'ctrl+\\+' Does TestCafe even support this key combination? T ...

Changes made to an array in a called method using TypeScript do not appear in the calling function

The angular 6 calling-component-code I'm working with is as follows: this.appDowntimeService.getAllApplications(this.message, this.appDetails); Here's the service method being called: async getAllApplications(message: any[], appDetails: any[ ...

Demonstrating the transformation of child elements into parent elements through angular 6 ngFor

I have a JSON array dataset where each object may contain nested arrays. In order to display the inner nested array elements as part of the parent array using Angular's NgFor, I need to format the input like this: [{ 'id': 1, 'tit ...

Serialising and deserialising TypeScript types in local storage

I'm currently working on a Typescript application where I store objects using local storage for development purposes. However, I've run into some trouble with deserialization. Specifically, I have an object called meeting of type MeetingModel: ...

Issues with Angular and Node Frameworks

Recently, I've been diving into learning Angular but have hit a roadblock with an error related to Angular. Here's the issue: I'm using Ubuntu 18.04 and installed the latest version of Node.js via nvm. However, I seem to have "two" nodes in ...

Managing the closest element depending on the selected option in Angular 5

My task involves accessing the nearest element of a dropdown. The HTML below includes multiple dropdowns and input boxes. When selecting options from the dropdown, I need to enable or disable the input box closest to it. <div class="form-block" *ngFor= ...

What is causing the malfunction in this overloaded function signature?

Encountering an issue when attempting to declare an overloading function type with a full type signature in TypeScript. For example: // Full type signatures for functions type CreateElement = { (tag : 'a') : HTMLAnchorElement, (tag ...

There was an issue retrieving the metadata for the bootstrap package using the git+ssh protocol

While attempting to install angular devkit and other dependencies using npm install, I encountered the following error message: Could not retrieve metadata for bootstrap@git+ssh://example@example.com/gios/Web-Standards-Bootstrap.git#05a343dddce91dd157702 ...

Transferring the storage value to an Ionic 2 object

Extracting information from storage in Ionic 2. this.storage.get('name').then((nama) => { this.name = nama }); Now, I am trying to assign the extracted data "this.name" to an object. However, upon running the app, ...

Is there a way to prevent this React function from continually re-rendering?

I recently created a small project on Codesandbox using React. The project involves a spaceship that should move around the screen based on arrow key inputs. I have implemented a function that detects key presses, specifically arrow keys, and updates the ...

The functionality of the Request interface appears to be malfunctioning

Hey there, I'm currently working on building an API using Express and TypeScript. My goal is to extend the Request object to include a user property. I've done some research on Google and found several posts on StackOverflow that explain how to d ...

How to handle a Node.js promise that times out if execution is not finished within a specified timeframe

return await new Promise(function (resolve, reject) { //some work goes here resolve(true) }); Using Delayed Timeout return await new Promise(function (resolve, reject) { //some work goes here setTimeout(function() { resolve(true); }, 5000); } ...

There are no functions or classes returned when using NPM Link with the module

Welcome. Whenever I run npm link ../folder/ToFolder, it works as expected. However, when I attempt to import any function, nothing is returned. A clearer explanation I have tried importing a module that I created from another folder using npm link. When ...

Using Lodash to Substitute a Value in an Array of Objects

Looking to update the values in an array of objects, specifically the created_at field with months like 'jan', 'Feb', etc.? One way is to loop through using map as demonstrated below. However, I'm curious if there's a more co ...

Integrating one service into another allows for seamless access to the imported service's properties and methods within an Angular

After reviewing the content at https://angular.io/guide/dependency-injection-in-action, it appears that what I am trying to achieve should be feasible. However, I encounter this error when attempting to invoke a method on my injected service from another s ...

Utilize Angular 2 routes within your express application

I've recently developed a web application that has the server-side built on Node.js and the client-side on Angular. The file structure of the project is as follows: |_ api |_ client |_ config |_ models |_ package.json |_ server.js However, I'm ...

Can observable data be saved into another observable data storage?

I attempted to retrieve the array of first names from the observable below, which receives its response from an API (hardcoded here). I aim to store the original data in a separate observable. Thus, my implementation is as follows: this.initialData = Obse ...

Clicking the button will trigger the onclick event

I'm working on a button component in TypeScript and I have encountered an issue with passing the event to the submitButton function. import * as React from 'react'; interface Props { className?: string; text: string; onClick?(event: Reac ...