t13878
t13878

Reputation: 11

Angular - pass file name to input text box upon upload

I am trying to upload a local file using angular. To do this I click on an input text box. Once the file has been uploaded I want to display the file name in the same input text box. How can I fill the input text box with the name of the chosen file?

My component .ts

import { Component, OnInit } from '@angular/core';
import { Module, ClientSideRowModelModule } from '@ag-grid-enterprise/all-modules';


@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {

  file: File;

  constructor() {

  }

  fileChange(file) {
    this.file = file.target.files[0];
    console.log(this.file.name);
  }

  ngOnInit() {
  }

}

And the .html

<div>
  <h4>Upload File</h4>
  <input type="file" style="display: none" #file (change)="fileChange($event)"/>
  <input type="text" (click)="file.click()">
</div>

I though that I could assign value=file.name somehow. But I couldn't figure out a way to do it.

Upvotes: 0

Views: 1719

Answers (1)

Hansaka Sandaruwan
Hansaka Sandaruwan

Reputation: 521

Add a ngModel to your text input.

filename: string;
  fileChange(file) {
    this.file = file.target.files[0];
    console.log(this.file.name);
    this.filename = this.file.name
  }
<div>
  <h4>Upload File</h4>
  <input type="file" style="display: none" #file (change)="fileChange($event)"/>
  <input type="text" (click)="file.click()" [(ngModel)]="filename">
</div>

Upvotes: 1

Related Questions