Angular 8/9 @Input, @Output and EventEmitter Tutorial by Quick Example

In a real-world Angular application, a number of components may exist with their own specific task to accomplish. This hierarchy of components may have parent-child or relation as siblings.

To communicate from parent to child component we use @Input decorator to pass data from parent to child component and to send back data from child to parent we use @Output decorator. The @Output emits the data using the EventEmitter method to the parent component.

Let’s create a demo on How we can use @Input, @Output and EventEmitter to data communication.

Here we will add two components Create Post and List Posts which will be in App Component.

 

Create Components

Run following NG generate commands in the terminal window to quickly create components in the posts folder:

PostCreateComponent

The app-post-create is having (postCreated) Output property to fetch created post data using the emit() method.

AppComponent

In the AppComponent we will just get newly created post emitted from PostCreateComponent then push it into a storedPosts object.

Then the storedPosts is passed to PostListComponent via [posts] input property.

PostListComponent

The app-post-list component directive is having [posts] input property to take in the emitted via AppComponent.

 

Leave a Reply

avatar
  Subscribe  
Notify of