Search code examples
angulartypescriptangular-materialangular8mat-list

Angular 8 Adding item to array and update the display in mat-list


I have a file upload component and, on the side, a mat-action-list that displays all of the files uploaded. When a user uploads one file, it adds it to the bottom of the list as expected. However, if they upload another file, it adds it to the bottom of the list but ALSO the previously uploaded file's name is changed to the one just uploaded. This will happen for every additional file uploaded! So if they upload 5 files, all five will display the last uploaded filename. If you leave the screen and go back to it, the list is correct.

HTML:
<mat-action-list class="fileList">
          <mat-list-item *ngFor="let file of arrApplicationFiles">
            <mat-icon mat-list-icon >folder</mat-icon>
              <h4 mat-line>{{file.fdFileName}}</h4>
          </mat-list-item>
        </mat-action-list>

Component method that gets called to add file:

  arrApplicationFiles: ApplicationFile[];

  public addNewFile(file: ApplicationFile) {
    this.arrApplicationFiles.push(this.applicationFile);

Here's the method that gets the initial list:

  public getUploadedFiles() {
    this.fileService.getFiles()
      .subscribe(
        res => {
          this.arrApplicationFiles = res;
        },
      error => {
        console.log('There was a problem retrieving files !!!' + error);
      });
  }
``

I expect it to add each added file to the bottom of the list without changing the previously added files.

Solution

  • You should push the file argument, not the this.applicationFile variable