Angular 5 EventEmitter from child to parent component emits undefined
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.
string
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?
2 Answers
2
You should be using $event
here:
$event
<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.
$event
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.
$event
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.
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
.
$
event
$event
$event
<d-table (sendDataEvent)="receiveBusinessCycle($event)"></d-table>
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.