Recently, I delved into the basics of Angular 4 and encountered a roadblock while trying to listen to an emitted event. Let me share a simple example that demonstrates the issue:
DateSenderComponent
is sending out the current date to be handled by its parent component AppComponent
(as shown below):
import { Component, Output } from '@angular/core';
import { EventEmitter } from "events";
@Component({
selector: 'app-date-sender',
template: '<button (click)="sendDate()">Send</button>'
})
export class DateSenderComponent {
@Output() dateSent = new EventEmitter();
sendDate(){
var dt = new Date();
console.log(dt);
this.dateSent.emit(dt.toString());
}
}
The role of AppComponent
is to capture the broadcasted date event:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: '<app-date-sender (dateSent)="dateReceived($event)"></app-date-sender>'
})
export class AppComponent {
dateReceived(value){
console.log('Result: ', value);
}
}
Following various beginner tutorials, I understood this method for event listening. However, upon loading the page, instead of displaying the received date value, I encounter the following error:
AppComponent.html:1 ERROR TypeError: instance[output.propName].subscribe is not a function
at createDirectiveInstance (core.es5.js:10727)
at createViewNodes (core.es5.js:12086)
at callViewAction (core.es5.js:12530)
at execComponentViewsAction (core.es5.js:12439)
at createViewNodes (core.es5.js:12113)
at createRootView (core.es5.js:11991)
at callWithDebugContext (core.es5.js:13206)
at Object.debugCreateRootView [as createRootView] (core.es5.js:12666)
at ComponentFactory_.create (core.es5.js:9912)
at ComponentFactoryBoundToModule.create (core.es5.js:3448)
Unfortunately, I could not find any clarifying information about this error or resolve it on my own.
One observation worth noting is that when I modify the template of AppComponent
to listen to an event that is not being emitted anywhere (for instance
<app-date-sender (someStringSent)="dateReceived($event)"></app-date-sender>
), the error disappears. This suggests a connection between the emitted output event and the template's listener, causing the problem.
Can someone provide guidance on how to address this issue?