Tuesday, August 25, 2020

Using EventEmitter with @Output

In the previous post, we saw what EventEmitters are and how they are used in combination with @Output decorator to handle communicate from Child component to the Parent component. In this post, we shall see a full example of how this is implemented.

In the example, we have a ParentComponent and a ChildComponent, the child component has a button and a @Output decorator. In the buttons click event, we will trigger the emit event of the EventEmitter associated with the @Output parameter, we will also send a payload along with the emit.

The emit event is handled in the parent component and the payload sent from the child component is displayed as a message in the parent component.

child.ts
import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.html',
  styleUrls: ['./child.css']
})
export class ChildComponent implements OnInit {
  @Output() handleClickEvent = new EventEmitter();
  childMessage: string;
  constructor() { }

  ngOnInit(): void {
    this.childMessage = 'Hello from Child Component';
  }
  handleButtonClick() {
    this.handleClickEvent.emit(this.childMessage);
  }
}

child.html
<div>
    <u>Child Component</u><br/>
    <input type="button" value="Click Me" (click)="handleButtonClick()"/>
</div>

parent.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.html'
})
export class ParentComponent implements OnInit {
  message: string;
  constructor() { }

  ngOnInit() { }

  displayMessage(strMessage) {
    this.message = strMessage;
  }

}

parent.html
<div>
    <u>Parent Component</u><br/><br/>
    <app-child (handleClickEvent)='displayMessage($event)'></app-child>
    <p>Message from Child Component: <u>{{message}}</u></p>
</div>

Output





Search Flipkart Products:
Flipkart.com

No comments: