简体   繁体   中英

reusing angular 9 component

I have a file upload component, app-file-upload that has a file type and a list of files variables. Everything works fine until I want to have multiple app-file-upload components on the same page.

What I am expecting is that when I click on the first file upload button, it would populate the list on the first app-file-upload . Then when I click on the second file upload button, the uploaded files would go to the second component's list.

What actually happens is that the second list of files would go to the first component's list. It is as if the second component is just a reference of the first.

Question: I know that angular services are created as singletons. So are components?? it wouldn't make sense because components are to be reused. Or am I doing something wrong?

Here a simple file upload component that works as you want.

Demo at this link: https://angular-upload-csvx.stackblitz.io/

Full code and extra: https://stackblitz.com/edit/angular-upload-csvx

//files.component.ts
import {Component} from '@angular/core';

@Component({
  'templateUrl': './files.component.html',
  'selector': 'app-files'
})

export class FilesComponent {
  handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    var file = files[0];
  }

}
<!--files.component.html-->
<div>
  <form>
    <div>
      <input type="file" (change)="handleFileSelect($event)">
    </div>
  </form>
</div>
<!--app.component.html-->
<div>
  <app-files></app-files>
  <hr>
  <app-files></app-files>
  <hr>
  <app-files></app-files>  
</div>

Thanks to @xDrago. I found the issue. I have a label that is for the input of type file (code below). All I need to do I generate a random number and assign to the for of the label and the id of the input .

 <label for="file-{{uniqueNumber}}" (click)="handleUploadClick()">
        <th-icon-upload></th-icon-upload>
        {{buttonText}}
    </label>
 <input type="file" id="file-{{uniqueNumber}}" [attr.multiple]="multiple ? '' : null" (change)="handleFileInput($event.target.files)" accept="{{acceptableFiles}}" 
        [attr.disabled]="successFilesCount >= maximumNumberOfFiles ? '' : null" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM