Angular 2 Component Communication with @Output()


Angular 2 Component Communication with @Output()

In last post we learnt about @Input() property and how to use @Input() directive. Here in this post we will learn Angular 2 Component Communication with @Output()

@Output decorator used to send data from child component to parent component, @Output directive notify changed data to parent components from child component.

@Output directive of Angular binds a property of the type with EventEmitter.

EventEmitter<> , Here <> indicates that which type of data you want to transfer from child to parent component.

Let’s understand @Output directive by one simple counter example. Here i am taking one simple example to increase counter value, this counter value will be passed from child to parent component.

Rules to use @Output directive

  1. Create Child Component.
  2. Create one EventEmitter variable with @Output and emit that variable inside method.
  3. Create parent component and get emitted data inside any method.
  4. Use EventEmittervariable with property binding in child selector and call parent component method inside EventEmittervariable property binding.

Example

  1. child.component.ts
  2. child.html
  3. parent.component.ts
  4. parent.html
  5. app.component.ts
  6. app.html

child.component.ts

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

@Component({
  selector:'child',
  templateUrl:`./child.html`
 })

export class ChildComponent {
  counter:number = 0;
  constructor() {}
  @Output() changeCounterValue: EventEmitter<number> = new EventEmitter();
  
  changeCounter():void {
    this.counter = this.counter + 1;
    this.changeCounterValue.emit(this.counter);
  }
}

child.html

<button (click)="changeCounter()">Click me</button>

parent.component.ts

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

@Component({
  selector:'parent',
  templateUrl:'./parent.html'
})

export class ParentComponent {
 counter:number = 0;
 constructor() {}

 displayCounter(count) {
   this.counter=count;
 }

}

parent.html

<child (changeCounterValue)="displayCounter($event)"></child>

<h1>{{counter}}</h1>






Full-stack web and mobile app development company Contact Us : Skype: indore.webcoder Email: info@w3sparks.com Sales: +91 8085506229