Search code examples
angulartypescripteventemitter

Angular - Output & Event Emitter showing undefined in parent


I want to allow users to upload a CSV file. I have my file input nested in the parent. I can console log the uploaded CSV file in the child component and see I have it fine but I receive undefined when I pass it through to the parent.

I guess I am not passing the correct value in the parent but I'm not sure what it should be.

child.component.html

<form class="mt-4" [formGroup]="csvForm" (ngSubmit)="uploadDocument()">
    <input type='file'
           name="fileUpload"
           id="txtFileUpload"
           #fileUpload
           (change)="changeListener($event)"
           accept=".csv"
           formControlName="csvFileUpload"
           required />
           
    <button (click)="uploadDocument(fileUpload.value)"
            type="submit">Upload
    </button>
</form>

child.component.ts

@Output() onSendCSV: EventEmitter<any> = new EventEmitter();

changeListener($event: any): void {
    const files = $event.srcElement.files;
    this.ngxCsvParser.parse(files[0], { header: this.header, delimiter: ',' })
        .pipe().subscribe((result: Array<any>) => {
            console.log('Result', result);
            this.csvRecords = result;
        }, (error: NgxCSVParserError) => {
            this.csvForm.controls['csvFileUpload'].setErrors({ csvFileUpload: true });
            console.log('Error', error);
        });
    }

uploadDocument(csvRecords: any) {
    this.onSendCSV.emit(csvRecords);
}

parent.component.html

<csv-upload (onSendCSV)="collectCSV($event)"></csv-upload>

parent.component.ts

fileUpload: any[];

collectCSV(fileUpload: any) {
        console.log(fileUpload);
    }

Solution

  • I am assuming that you've a property name csvRecords in your component class. So try emitting the csvRecords in your event emitter.

    this.onSendCSV.emit(this.csvRecords)