简体   繁体   English

重用 angular 9 组件

[英]reusing angular 9 component

I have a file upload component, app-file-upload that has a file type and a list of files variables.我有一个文件上传组件app-file-upload ,它具有文件类型和文件变量列表。 Everything works fine until I want to have multiple app-file-upload components on the same page.一切正常,直到我想在同一页面上有多个app-file-upload组件。

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 .我期望的是,当我点击第一个文件上传按钮时,它会填充第一个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.问题:我知道 Angular 服务是作为单例创建的。 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/此链接的演示: https : //angular-upload-csvx.stackblitz.io/

Full code and extra: https://stackblitz.com/edit/angular-upload-csvx完整代码和额外代码: 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.感谢@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 .我需要做的就是生成一个随机数并分配给labelforinputid

 <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" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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