Search code examples
javascriptangulartypescriptangular-event-emitter

Emitted Event could not result in calling the bound method


in the below code i want i have an EventEmitter object as shown in the method onSubmitPost(). when i compile the code the logs in the method onSubmitPost gets displayed. but the logs in the method onReceiveSubmittedEvtEmitter never get displayed. In the follwoing html code

    <app-post-create (onPostSubmittedEvtEmitter)="onReceiveSubmittedEvtEmitter($event)"></app-post-create>

method onReceiveSubmittedEvtEmitter should gets executed when the Event onPodtSubmittedEvtEmitter is emitted, but since i do not receive the logs from the method onReceiveSubmittedEvtEmitter, i expect that the event has not been emitted. please let me know why the event has not been emitted and how to fix it

post-create.component.ts:

//logs in this method are displayed
onSubmitPost(post: Post) {
this.post = {
  title: this.post.title,
  content: this.post.content
};
this.onPostSubmittedEvtEmitter.emit(this.post);
console.log("onSubmit->: post.title: " + post.title);
console.log("onSubmit->: post.content:" + post.content);
}

post-create.component.html:

<form>
<div class="form-group">
  <label>Title</label>
  <input type="text" class="form-control" name="title" required [(ngModel)]="post.title">
</div>
<div class="form-group">
  <label>Content</label>
  <textarea name="content" class="form-control" cols="10" rows="2" required [(ngModel)]="post.content"></textarea>
</div>
<button type="submit" class="btn btn-primary" (click)="onSubmitPost(post)">Create</button>
</form>

app.component.ts:

//console logs do not get displayed
import { Component } from '@angular/core';
import { Post } from './post-create/post-create.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'binding2';
  postsArray: Post[] = [];

  onReceiveSubmittedEvtEmitter(post: Post) {
    this.postsArray.push(post);
    console.log("onReceiveSubmittedEvtEmitter->: post.title: " + post.title);
    console.log("onReceiveSubmittedEvtEmitter->: post.content:" + post.content);
  }
}

app.component.html:

<app-post-create (onPostSubmittedEvtEmitter)="onReceiveSubmittedEvtEmitter($event)"></app-post-create>
<app-post-list [postsToAddToList]="postsArray"></app-post-list>

Solution

  • I have just found the answer as i am trying to solve it. just decorate the EventEmitter with

    @Output
    

    as follows:

      @Output() onPostSubmittedEvtEmitter: EventEmitter<Post> = new 
      EventEmitter<Post>();