In the following code snippet, I am trying to use an EventEmitter object in the onSubmitPost() method. When I compile the code, the logs in the onSubmitPost method are displayed correctly. However, the logs in the onReceiveSubmittedEvtEmitter method never appear. The HTML code below shows how the EventEmitter is used:
<app-post-create (onPostSubmittedEvtEmitter)="onReceiveSubmittedEvtEmitter($event)"></app-post-create>
The onReceiveSubmittedEvtEmitter method should execute when the event onPostSubmittedEvtEmitter is emitted. Since I do not see any logs from this method, I suspect that the event has not been emitted. Can you please help me understand why the event is not being 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="amp-form-control" name="title" required [(ngModel)]="post.title">
</div>
<div class="form-group">
<label>Content</label>
<textarea name="content" class="amp-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 are not 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>