1

I want to build a component that processes user input from a textarea and serves it to the user as a (txt) file in Angular 9.

The form in app.component.html looks like this:

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

My app.component.ts looks 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
  }
}

How can I create a file with Angular based on the user input entered in the form and serve it to the user?

Tom
  • 1,358
  • 2
  • 14
  • 36

1 Answers1

4

You need to add following function in your ts file and call it from submit, It won't ask for location to save the file, as by defaults file will be saved in your download folder

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); 
}

Stackblitz example: https://stackblitz.com/edit/angular-bpbexb

Kiran Shinde
  • 5,732
  • 4
  • 24
  • 41
  • Thank very much, this already helped me a lot. One small thing: I want to display the form conditionally with a *ngIf directive like here: https://stackblitz.com/edit/angular-dwzupk But I'm getting a this.myForm is undefined error. What is missing? – Tom Apr 15 '20 at 11:38
  • You can take reference from here https://stackoverflow.com/questions/55610047/angular6-viewchild-undefined-with-ngif – Kiran Shinde Apr 15 '20 at 15:13