Parent and Child Component Communication via @Input(), @Output() and EventEmitter

app.component.html

<H1>Welcome! {{message}}</H1>
<app-child (childEvent)="message=$event" [parentData]="name" ></app-child>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public name = 'Tyson';
  title = 'ComponentComm';
  public message = '';
}

child.component.html

<p>Hello {{parentData}}</p>
<button (click)="fireEmitter()">Click</button>

child.component.ts

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

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

  @Input() public parentData: string;

  @Output() public childEvent = new EventEmitter();

  constructor() { }

  ngOnInit() {
  }

  fireEmitter(){
    this.childEvent.emit('Hello Parent Component');
  }
}

Leave a Comment