'Angular function shows updated value first time only
html
<input type="file" [(ngModel)]="profile.myFile1" (change)="handleFileInfo($event.target.files, 'myFile1')">
<div *ngIf="filesExists('myFile1')">
<span>Size: {{getFileSize('myFile1')}}</span>
</div>
<input type="file" [(ngModel)]="profile.myFile2" (change)="handleFileInfo($event.target.files, 'myFile2')">
<div *ngIf="filesExists('myFile2')">
<span class="photo-size">Size: {{getFileSize('myFile2')}}</span>
</div>
ts file code
handleFileInfo(files: FileList, fileTypeName: string) {
// Other code ....
let fileObj: FileObj = { type: fileTypeName, file: files.item(0), fileSizeText: fileSizeText, isValid: validSizeFlag };
this.commonService.addOrReplaceFiles(this.files, fileObj); //Add or update the object array with the file fileObj
}
getFileSize(fileTypeName: string) {
let fileObj = this.files.find(o => o.type === fileTypeName); //this.files : Object array
return fileObj.fileSizeText;
}
I have multiple file upload fields. If I upload a file it shows the file size. If I reupload the file again it shows the new file preview. But the getFileSize() function value never gets updated, it shows first uploaded file size.
Solution 1:[1]
getFileSize only gets called the first time the HTML is rendered. It has no way to know if your myFile1 has changed. I suggest having a myFile1Size variable that gets updated in your TS code whenever you upload a new file to hold the information about the size and bind that into the HTML as {{myFile1Size}}.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tu Nguyen |
