Angular2中有两个组件会干扰文件事件 [英] Two components interfering file events in Angular2

查看:26
本文介绍了Angular2中有两个组件会干扰文件事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 FileUploadComponent 的组件的两个实例,它们的职责是侦听文件事件(这是一个简单的模板,其中包含带有文件上载按钮的表单,如下所示),并将这些事件发送给其托管组件通过 EventEmitter .

I have two instances of a component called FileUploadComponent, whose responsibility is to listen for file events (it's a simple template that contains a form with a file upload button as shown below) and emit those to its hosting component via an EventEmitter.

看起来很简单,当我将其中两个组件(Comp1,Comp2)添加到模板中时,页面上按钮的第一个实例似乎接收了所有事件,即使该组件的单独实例也是如此.

Simple as it seems, when I add two of those components (Comp1, Comp2) into a template, the first instance of the button on the page seems to receive all events even from separate instances of this particular component.

因此可视化:

Comp1 ----------------------  / EventEmitter Fired 
Comp2 -- File uploaded ----- / -------

在这里您可以看到 Comp1 从此 FileUploadComponent 的后续实例接收到一个事件,为什么?

Here you can see that Comp1 receives an event from subsequent instances of this FileUploadComponent, why is that ?

以下是文件:

file_upload_button.component.ts (为简洁起见,省略了组件装饰器)

export class FileUploadButtonComponent {

  @Output() filesChanged = new EventEmitter<File[]>();
  private _files: File[];

  fileUpload(event: FileReaderEvent) {

    console.log(this); // !!! ====> this already triggers in the wrong component!

    this._files = event.target.files;
    this.filesChanged.emit(this._files);
  }
}


按钮模板:


Template for button:

file_upload_button.html

<form>
  <input type="file" multiple name="file" (change)="fileUpload($event)" id="file"/>
</form>


主机模板:


Host template:

some_host.html

// first instance
<file-upload-button (filesChanged)="filesChangedFunc($event)"><file-upload-button>
// second instance
<file-upload-button (filesChanged)="anotherFilesChangedFunc($event)"><file-upload-button>

当我单击第二个按钮时,第一个实例认为自己负责,上面代码中的 console.log(...)提到了这一点.在花了几个小时的时间看完这段代码后,我对这里发生的事情没有任何理智的解释.

When I click the second button, the first instance sees itself responsible, the console.log(...) in the above code mentions that. Having gone over this code for several hours I have no sane explanation for what is happening here.

http://plnkr.co/edit/7jzjL8dRsCFPUMrVb0I9?p=preview

推荐答案

这是因为您在元素上分别具有相同的 id for .

That's because you have the same id and for respectively on your elements.

您必须使用唯一的ID:

You have to use unique id:

app/file_upload_button.component.ts

let uniqueId = 0;

@Component({
  selector: 'file-upload-button',
  templateUrl: 'app/file_upload_button.html',
  styleUrls: [ 'app/file_upload_button.css' ]
})
export class FileUploadButtonComponent {
  id = `file-upload-${uniqueId++}`;

app/file_upload_button.html

<input type="file" [name]="'name' + id" [id]="id" .../>
<label [attr.for]="id" ...

柱塞

Plunker

这篇关于Angular2中有两个组件会干扰文件事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆