Angular 2 Component Communication


Angular 2 Component Communication

Angular 2 Component Communication helps us to communicate between parent component to child component.

Child component can interact with a parent component using the @Input() property and Parent component can interact with child component using @Output property.

In this post i will focus on how to interact with a parent component to child component using @Input() property.

Rules to remember:

  1. Child component must be placed inside parent component.
  2. Child component variable which is declared with @Input decorator should be bind with property binding inside child component.
  3. Parent component variable name should be inside the property binding.

Let’s take one simple example suppose we have two component one is parent component and another is child component and we want to exchange data from parent to child component.

Example

  1. parent.component.ts
  2. parent.html
  3. child.component.ts
  4. child.html

parent.component.ts

import { Component } from '@angular/core';
@Component({
selector:'parent',
templateUrl:'./parent.html'
})

export class ParentComponent {
   parentMessage:string = "Message from parent component";
   
   constructor() {}
}

parent.html

<child [childMessage]="parentMessage"></child>

Here childMessage is coming from child component and parentMessage is coming from parent component.

Here [childMessage] is nothing but property binding.

child.component.ts

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

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

export class ChildComponent {
  @Input() childMessage: string;
  constructor() {}
}

child.html

<p>{{ childMessage }}</p>

Output

Message from parent component






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