Olive
Olive

Reputation: 159

How to display selected file in label instead of input tag in angular 6

I should display the selected file name in label tag instead of displaying in the input tag. Can you please help me to achieve this. Thanks in advance

My code looks like below,

<div *ngFor='let item of list; let i = index'>
  <input #fileInput type="file"  />
  <button type="button" (click)="fileInput.click()">trigger</button>
  <button type="button" (click)="reset(fileInput, i)">Reset</button>
</div>

I have tried changing input tag to label but it's not working. Could you please help me to achieve it. Thanks in advance.

Upvotes: 1

Views: 4581

Answers (3)

Ganesh
Ganesh

Reputation: 6016

try this once..

This will display the name of the file you have selected.

In Template

<div *ngFor='let item of list; let i = index'>
  <span *ngIf="selectedLogoFile[i]">{{selectedLogoFile[i].name}}</span>
  <input style="display: none" type="file" (change)="onFileChanged($event,i)" #fileInput>
  <button type="button" (click)="fileInput.click()">trigger</button>
  <button type="button" (click)="reset(fileInput, i)">Reset</button>
</div>

In Component

  selectedLogoFile: File[]= [];

  onFileChanged(event: any,index: any) {
    this.selectedLogoFile.push(event.target.files[i]);
    console.log(this.selectedLogoFile[i].name);
  }

hope this will give you an idea to solve your issue.. :)

Upvotes: 2

kaminarifox
kaminarifox

Reputation: 433

  • You can hide input and wrap it with label
  • Bind variable to input with [(ngModel)]
<label> {{fileName}}
  <input #fileInput type="file" [(ngModel)]="selectedFile" [style.display]="'none'">
</label>

and make getter

get fileName(): string {
  return this.selectedFile ? this.selectedFile.split('/').pop() : 'Select file';
}

then use this getter in any tag like {{ fileName }}

Upvotes: 1

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

Try this code.I hope it will helps you.

HTML:

 <div>
        <div>
            <input #fileInput type="file" (change)="fileProgress($event)" />
            <button type="button" (click)="fileInput.click()">trigger</button>
            <button type="button" (click)="reset(fileInput, i)">Reset</button>
        </div>
        <span *ngIf="fileName">{{fileName}}</span>
    </div>

TS:

fileProgress(fileInput: any) {
    let file = fileInput.target.files[0];
     this.fileName = file.name;
    console.log(this.fileName)
}

Upvotes: 3

Related Questions