@output decorator in Angular 4
The @output decorator in angular 4 used to emit the event from child to parent.
The basic parent-child and child-parent communication by introducing
EventEmitter
and @Output
The child component exposes an EventEmitter property with which it emits events when we click the click me button. The parent binds to that event property and display the message.
<child (message)="onNotifyclick($event)"></child>
it means you can pass the event into your parent component itself not a HTML element.
Parent Component
import { Component } from '@angular/core'; /** * App Component * Top Level Component */ @Component({ selector: 'app', styleUrls: ['./app.component.css'], template: ` <h1>welcome</h1> <child (message)="onNotifyclick($event)"></child> <p>{{message}}</p> ` }) export class AppComponent { outputmsg:string; constructor() { } onNotifyclick(message:string):void{ this.outputmsg = message; } }
Chaild Component
Need to import the @output,EventEmitter decorations.
import { output ,EventEmitter } from '@angular/core'; @child.component.ts import { Component, output, EventEmitter } from '@angular/core'; /** * App Component * Top Level Component */ @Component({ selector: 'child', styleUrls: ['./child.component.css'], templateUrl: `./child.component.html` }) export class ChildComponent { @Output() message: EventEmitter<string> = new EventEmitter<string>(); constructor( ) { } clickme():void{ this.message.emit("Hi Ajay"); } }
child.component.html
<button (click)="clickme()">Click Me</button>
Output
Hi Ajay// this value passed from parent