Handle child component events in the parent component
You can listen to the child component events in the parent component using the EventEmitter property exposed in the child component.
As the Child component will emit the events to the parent component, there will an output property in the child component. You can declare an Output property using the @Output decorator.
Event emitted from the child component can be handled with the event binding in the parent component.
Child Component
To use the EventEmmiter, your need to import it from the Angular Core library. Then create an instance of the EventEmitter with the type of the field you are going to emit.
In the below example, we want to emit the value of field "likeStatus" so that the parent component can use it to either increase likes or the dislikes count.
user-input.component.ts
import { Component, OnInit, Input,Output,EventEmitter } from '@angular/core'; @Component({ selector: 'app-user-input', template: ` <button (click) = "Like(true)" > Like </button> | <button (click) = "Like(false)"> Dislike </button> ` , styleUrls: ['./user-input.component.css'] }) export class UserInputComponent { @Output() LikeStatusEmitter =new EventEmitter<boolean>(); Like(likeStatus: boolean) { this.LikeStatusEmitter.emit(likeStatus); } }
Note: In the above example, we are using the Inline template of the component so we wrote our HTML inline.
Parent Component
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <p>This post is liked {{ likesCounter }} times. </p> <p>This post is disliked {{ disLikesCounter }} times. </p> <hr> <app-user-input (LikeStatusEmitter) = onLiked($event) ></app-user-input> ` , styleUrls: ['./app.component.css'] }) export class AppComponent { likesCounter : number=0; disLikesCounter : number = 0; onLiked(likedStatus: boolean){ likedStatus ? this.likesCounter ++ :this.disLikesCounter++; } }
Output:
0 Comments