Search code examples
angulartypescripteventemitter

output event emmiter throws an error in Angular 5


I'm having a weird issue, I have a project in Angular 5.2.11 with a parent and child components. Everything was working fine until I've added an @Output decorator in the child component to emmit a response to the parent component. This is is the child TS:

questionCorrectAnswer:number;

nextQuestion(){
   this.nextQuestionEvent.emit({});
}

This is the child's HTML

<a (click)="nextQuestion()" class="btn btn-primary">Go to next question</a>

In the parent's HTML I have this:

<app-question-displayer (nextQuestionEvent)="nextQuestion($event)"></app-question-displayer>

And finally the parent's TS file is the following:

setQuestion(idx:number){
   this.currentQuestion=this.exam.questions[idx];
   this.questionDisplay.setupQuestion(this.currentQuestion);
}

nextQuestion(event){
   this.currentQuestionIndex++;
   this.setQuestion(  this.currentQuestionIndex);
}

And as soon as the page loads, it redirects me to the home page and in Chrome's Console I see this error:

enter image description here

As you can see it is not a very descriptive error since I have googled it but found other errors that do not have much to do with mine.

There is something curious, if I remove the event listener (nextQuestionEvent)="nextQuestion($event)" in the app-question-displayer tag, the app does not crash.

What do you think it can be??

Thanks in advance!

Edit:

This is the Output definiton:

  @Output() nextQuestionEvent:EventEmitter<any>;

Solution

  • You have not instantiated your EventEmitter.

    Use the following code to do that:

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