Search code examples
angularconstructorsingletonngforng2-file-upload

ng2-file-upload, new FileUpload() does not create new instance for an additional component, when looping with *ngFor


I have multiple formats, which i loop over (with ngFor) to create new components. Every component has the ng2-file-upload implemented via the constructor (new FileUploader()).

However, if I add a new file and display it, it is also added/displayed on the uploader of the other components, which should not be the case.

What did is miss?

https://stackblitz.com/edit/angular-i8oc1r


Solution

  • Okay, I'll answer this one, on behalf of someone who helped me from an angular chat group. (many thanks!)

    The problem seems to be that, although two distinct empty arrays are provided

    <upload
      *ngFor = "let format of formats"
      [images] = "images ? images : []"
      [format] = format>
    </upload>
    

    or even better to see:

    <upload
      [images] = "[]"
      [format] = "'A'">
    </upload>
    
    <upload
      [images] = "[]"
      [format] = "'B'">
    </upload>
    

    angular just references the second empty array, instead of creating a new one. maybe i lack the experience, but thats not intuitive at all.

    the solution is, giving an empty array with different empty arrays inside...

    <upload
      *ngFor = "let format of formats; let i = index;"
      [images] = "images[i]"
      [format] = format>
    </upload>
    

    asdasd

    export class AppComponent  {
      ...
      images = [[],[]];
      ...
    }