In this article, we will learn how to pass data from child component to parent component using @Output() and EventEmitter in Angular 9.

@Output() allow Angular to share data between the parent context and child directives or components. An @Output() property is observable.

Use the @Output() decorator in the child component or directive to allow data to flow from the child out to the parent. An @Output() property should normally be initialized to an Angular EventEmitter with values flowing out of the component as events.

Prerequisites:

  • Basic knowledge of Angular
  • Code editor like Visual Studio Code

Create a new Angular project by typing the following command in the VSCode terminal.

ng new child-to-parent

Now, open the newly created project and execute the commands given below. It will create two components parent and child.

ng g c parent
ng g c child

Open the parent.component.ts file and add the code in it.

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

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {

  message: string;

  constructor() { }

  ngOnInit(): void {
  }

  getChildData($event) {
    this.message = $event
  }

}

Open the parent.component.html file and add the code in it.

<app-child (dataEvent)="getChildData($event)"></app-child>
<p>{{message}}</p>

Open the child.component.ts file and add the code in it.

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  data: string = "The Code Hubs";
  @Output() dataEvent = new EventEmitter<string>();

  constructor() { }

  ngOnInit(): void {
  }

  sendData() {
    this.dataEvent.emit(this.data);
  }

}

Open the child.component.html file and add the code in it.

<button (click)="sendData()">Get Data</button>

Open the app-routing.module.ts file and add the code in it.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ParentComponent } from './parent/parent.component';
import { ChildComponent } from './child/child.component';

const routes: Routes = [
  {
    path: 'parent',
    component: ParentComponent,
  },
  {
    path: 'child',
    component: ChildComponent,
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Open the app.component.html file and add the code in it.

<router-outlet></router-outlet>

Output:

 

Please give your valuable feedback and if you have any questions or issues about this article, please let me know.

Also, check Pass Data From Parent Component To Child Component Using @Input() In Angular 9

Footer Logo

Subscribe

Select Categories