Parent-to-child communication

Sends data or instructions from a parent component to a child. Usually using Input Properties and @Input() Decorator. Parent components can feed child components data via input attributes. @Input() decorates child components with input properties

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

Child Component

@Component({
    selector: 'app-child',
    template: `
        <p>Child Component: {{ childMessage }}</p>
  `
})
export class ChildComponent {
 @Input() childMessage: string;
}

Parent component

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

@Component({
  selector: 'app-parent',
  template: `
        <app-child [childMessage]="parentMessage"></app-child>
  `
})
export class ParentComponent {
  parentMessage = "Hello from Parent!";
}

 

Parent-Child Communication 

Sends data or events from a child component to a parent. The EventEmitter class, Output Properties, and @Output() Decorator do this.

Child Component

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


@Component({
  selector: 'app-child',
  template: `
      <button (click)="sendToParent()">Send to Parent</button>
  `
})
export class ChildComponent {
  @Output() messageToParent = new EventEmitter<string>();

  sendToParent() {
      this.messageToParent.emit("Hello from Child!");
  }
}

Parent Component

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

@Component({
  selector: 'app-parent',
  template: `
    <h1>Parent Component</h1>
    <app-child (messageToParent)="receiveFromChild($event)"></app-child>
    <p>{{ messageFromChild }}</p>
  `
})
export class ParentComponent {
  messageFromChild = "";
  receiveFromChild(message: string) {
    this.messageFromChild = message;
  }
}

bond to messageToParent output property in child component and respond to events to update messageParent component's fromChild.

 

 

 


Related Question