I am facing an issue with having two instances of a component named FileUploadComponent
. The purpose of this component is to listen for file events and emit them to its hosting component using an EventEmitter
.
Despite its seemingly simple functionality, when I introduce two instances of the component (Comp1, Comp2) into a template, the first instance seems to receive all events, even from separate components.
To illustrate the issue:
Comp1 ---------------------- / EventEmitter Fired
Comp2 -- File uploaded ----- / -------
In this scenario, Comp1
is receiving events from subsequent instances of the FileUploadComponent
, which is unexpected behavior. But why is this happening?
Below are the relevant files for reference:
file_upload_button.component.ts (Component Decorator omitted for brevity)
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>
When I click the second button, the first instance erroneously detects itself as responsible, as indicated by the console.log(...)
output in the code snippet above. Despite thoroughly reviewing the code for hours, I am unable to provide a logical explanation for this unexpected behavior.