Share File data between components angular

Viewed 187

I am using a reactive form to capture some inputs and a file from a user using a component The ts and html pages of the component is like below

    import {  Component, OnInit } from '@angular/core';
    import { FormBuilder, FormGroup } from '@angular/forms';
    import { Router, ActivatedRoute } from '@angular/router';

    @Component({
      selector: 'app-import-file',
      templateUrl: './import-file.component.html',
      styleUrls: ['./import-file.component.css']
    })
    export class ImportFileComponent implements OnInit {

      orderImportForm: FormGroup; 
      public importFile: File;

      constructor(private router: Router, private route: ActivatedRoute,private fb: FormBuilder) {
      }

      getfile(e: any) {
        const fileList: FileList = e.target.files;
        this.importFile = fileList[0]; 
      }

      ngOnInit(): void { 
        this.orderImportForm = this.fb.group({
          yourReferenceNumber: [''],
          orderType: ['']
        }); 
      }

      onSubmit() {
        console.log(this.importFile); // this will give you the file    
        console.log(this.orderImportForm.value);        
        if (this.importFile?.type=="pdf") {
          this.router.navigate(['../component1'], { relativeTo: this.route });
        }
        else {
          this.router.navigate(['../component2'], { relativeTo: this.route });      
        }
      }
    } 


    // HTML 


    <form [formGroup]="orderImportForm" (ngSubmit)="onSubmit()">
      <div class="row">
        <div class="col-sm-12 col-lg-6">
          <h2>Import a Purchase Order</h2>
          <div class="bg-light card">
            <div class="card-body">
              <fieldset class="form-group">
                <legend>Upload Reference No</legend>
                <div class="form-group">
                  <input type="text" class="form-control" formControlName="yourReferenceNumber">
                </div>
              </fieldset>

              <fieldset class="form-group">
                <legend>CSV Excel Or PDF File</legend>
                <div class="form-group">
                  <input type="file" (change)="getfile($event)" class="form-control-file" />
                </div>
              </fieldset>

              <fieldset class="form-group">
                <legend>Upload Type?</legend>
                <div class="form-check form-check-inline">
                  <label class="form-check-label">
                    <input type="radio" class="form-check-input" name="orderType" formControlName="orderType" value="1" />
                    Instant
                  </label>
                </div>
                <div class="form-check form-check-inline">
                  <label class="form-check-label">
                    <input type="radio" class="form-check-input" name="orderType" formControlName="orderType" value="2" />
                    Later
                  </label>
                </div>
              </fieldset>

            </div>
          </div>
        </div>   
      </div>
      <div class="row">
        <div class="col-sm-12 col-lg-6">
          <p class="my-5">
            <button class="btn btn-primary" type="submit">Submit</button>
          </p>     
        </div>
      </div>

    </form>

On form submission the values of file and form elements is getting captured correctly. As next step i have to load another component based on file type (if pdf file is uploaded showing component1 , otherwise showiing component2 )

Inside these components i have to read the file contents and process further. How can i read the content of importFile on another components ?

1 Answers

This problem has probably more than one solution, but when reading your question I was thinking of creating a service. Unlike components, services are injectable which means multiple other components can use the contents of a service.

I would create an Observable inside this service to which you emit for example importFile or anything you want basically whenever you want. From another component you import this service and subscribe to the observable. Then once a value is emitted on it you catch it and handle it in whatever way you want.

In case of the two possible components you might want to do something with *ngIf and async pipe.

Everything related to observables can be found here: https://rxjs.dev/guide/observable The rest is just native Angular stuff.

Related