I am trying to display the selected files name in a separate label using then InnerHtml property, however nothing is displaying on change (when file is uploaded) and I get an error "ERROR TypeError: Cannot set property 'innerHTML' of null".
My HTML (The input and corresponding label)
<button class="image-upload-button" mat-stroked-button (click)="fileUploader.click()" color="primary">Upload Image</button>
<label for="fileUploader" id="file"></label>
<input type="file" accept="image/*" #fileUploader id="fileUploader" (change)="displayFileName($event)" (change)="showPreview($event)" style="display: none;">
My goal is to set the label with the id "file" to show the name of the file uploaded / chosen using the file input. The button is simply a means to open the file explorer.
The on change function "displayFileName($event)" is responsible for setting the value of the label when a new file is uploaded.
DisplayFileName:
displayFileName(fileInput: Event) {
let file = (fileInput.target as HTMLInputElement).files![0];
let fileName = file.name;
console.log(fileName);
const element: HTMLElement = document.getElementById('#file') as HTMLElement;
element.innerHTML = fileName;
}
The console logs exactly what I need to display, although I still get the error regardless. What am I doing wrong here?
The syntax for getElementById is wrong, you only pass in the name of the id. That is why element was null.
const element: HTMLElement = document.getElementById('file') as HTMLElement;
Also, use it is a good practice to check if element exist or not , so it can be something like
if(element)
element.innerHTML = fileName;