Return to site

ANGULAR TIP: Output Decorator

1️⃣ Definition

@Output decorator is used to pass the data from child to parent component.

@Output decorator binds a property of a component, to send data from one component to the calling component.

@Output binds a property of the type of angular EventEmitter class.

 

 

2️⃣ Snippet

👉 Child component controller, 𝘸𝘩𝘦𝘳𝘦 𝘸𝘦 𝘴𝘦𝘯𝘥 𝘵𝘩𝘦 𝘦𝘷𝘦𝘯𝘵 𝘤𝘢𝘶𝘴𝘪𝘯𝘨 𝘵𝘩𝘦 𝘤𝘩𝘢𝘯𝘨𝘦

import { Component, Input, Output,EventEmitter, OnInit } from '@angular/core';  
  
@Component({  
  selector: 'app-student',  
   templateUrl: './student.component.html',  
   styleUrls: ['./student.component.css']  
})  
export class StudentComponent implements OnInit {  
   @Input() myinputMsg:string;  
   @𝗢𝘂𝘁𝗽𝘂𝘁() 𝗺𝘆𝗢𝘂𝘁𝗽𝘂𝘁:𝗘𝘃𝗲𝗻𝘁𝗘𝗺𝗶𝘁𝘁𝗲𝗿<𝘀𝘁𝗿𝗶𝗻𝗴>= 𝗻𝗲𝘄 𝗘𝘃𝗲𝗻𝘁𝗘𝗺𝗶𝘁𝘁𝗲𝗿();  
  outputMessage:string="I am child component."  
   constructor() { }  
  
  ngOnInit() {  
    console.log(this.myinputMsg);  
   }  
  
   𝐬𝐞𝐧𝐝𝐕𝐚𝐥𝐮𝐞𝐬(){  
     𝐭𝐡𝐢𝐬.𝐦𝐲𝐎𝐮𝐭𝐩𝐮𝐭.𝐞𝐦𝐢𝐭(𝐭𝐡𝐢𝐬.𝐨𝐮𝐭𝐩𝐮𝐭𝐌𝐞𝐬𝐬𝐚𝐠𝐞);  
   }

 

👉 Child component template, 𝘸𝘩𝘦𝘳𝘦 𝘵𝘩𝘦 𝘎𝘜𝘐 𝘵𝘳𝘪𝘨𝘨𝘦𝘳𝘴 𝘵𝘩𝘦 𝘤𝘩𝘢𝘯𝘨𝘦

<button (click)="𝘀𝗲𝗻𝗱𝗩𝗮𝗹𝘂𝗲𝘀"> Send Data </button>

 

👉 Parent component template, 𝘸𝘩𝘦𝘳𝘦 𝘸𝘦 𝘱𝘶𝘵 𝘵𝘩𝘦 𝘤𝘩𝘪𝘭𝘥 𝘤𝘰𝘮𝘱𝘰𝘯𝘦𝘯𝘵 𝘵𝘢𝘨 𝘣𝘰𝘶𝘯𝘥 𝘵𝘰 𝘵𝘩𝘦 𝘱𝘢𝘳𝘦𝘯𝘵

<app-student [myinputMsg]="myInputMessage" (𝗺𝘆𝗢𝘂𝘁𝗽𝘂𝘁) ="𝗚𝗲𝘁𝗖𝗵𝗶𝗹𝗱𝗗𝗮𝘁𝗮($𝗲𝘃𝗲𝗻𝘁)"></app-student>

 

 

👉 Parent component controller, 𝘸𝘩𝘦𝘳𝘦 𝘸𝘦 𝘤𝘢𝘵𝘤𝘩 𝘵𝘩𝘦 𝘦𝘷𝘦𝘯𝘵 𝘴𝘦𝘯𝘵 𝘣𝘺 𝘵𝘩𝘦 𝘤𝘩𝘪𝘭𝘥

import { Component } from '@angular/core'

@Component({
   selector: 'app-root'.
   templateUrl: './app-component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title ='AngApp';
   myInputMessage: string = 'I am parent component.';

   𝐆𝐞𝐭𝐂𝐡𝐢𝐥𝐝𝐃𝐚𝐭𝐚(𝐝𝐚𝐭𝐚){
       𝐜𝐨𝐧𝐬𝐨𝐥𝐞.𝐥𝐨𝐠(𝐝𝐚𝐭𝐚);
    }
}