Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 EventEmitter from child to parent component emits undefined

I am trying to send a string from a child component to his parent component.

Here is the child :

//imports... 

    @Component({
    selector: 'child',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.css'],
    providers: [ChildService]
    })

export class DataTableComponent implements OnInit {
    constructor(private http: HttpClient, private childService : ChildService) {}

    myMap = new Map<string, ISomeInterface>();
    currentSelection: string;

    @Output() sendDataEvent = new EventEmitter<string>();

    sendData() {
        console.log("sending this data:  " + this.myMap.get(this.currentSelection).name);
        this.sendDataEvent.emit(this.myMap.get(this.currentSelection).name);
    }
}

Here is the parent :

html ->

<d-table (sendDataEvent)="receiveBusinessCycle(event)"></d-table>

typescript ->

//imports...

@Component({
  selector: 'parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css'],
  providers: [ParentService]
})
export class MyParentComponent {
  totoName: string;

  constructor(private parentService : ParentService) {  }

  receiveBusinessCycle($event) {
    console.log($event); //shows in console 'undefined'
    console.log($event as string); 
    this.totoName = $event;
  }

}

The issue is that I am getting an undefined event when receiving the data in the parent component, here console logs :

sending this data:  201808
main.bundle.js:2328 undefined
main.bundle.js:2329 undefined

Any ideas on the issue?

like image 835
Logan Wlv Avatar asked Dec 18 '22 21:12

Logan Wlv


2 Answers

You should be using $event here:

<d-table (sendDataEvent)="receiveBusinessCycle($event)"></d-table>

I've faced a similar situation before and apparently, it seems to only work with $event as it is a reserved keyword to grab the event object.

Apparent, Angular provides a corresponding DOM event object in the $event only. That's why passing in any other variable as an argument won't work. You can read more about it here.

Angular also considers this as a dubious practice when working with native HTML Elements as it breaks the separation of concerns between the template and the component. Angular recommends the use of Template Variables instead. Read more about it here.

like image 145
SiddAjmera Avatar answered Dec 28 '22 10:12

SiddAjmera


You missed $ prefix of the event. $event is a reserved word, so your data is visible to the event handler in the component markup only with name $event.

<d-table (sendDataEvent)="receiveBusinessCycle($event)"></d-table>
like image 24
Suren Srapyan Avatar answered Dec 28 '22 10:12

Suren Srapyan