Communication pattern between Parent and Child using @Input

There are many ways that we can communicate from parent to child or share the data. We will discuss briefly as we proceed one by one.

 

Using @Input decorator

We use @input decorator in the child component class by 

@Input('data') value:any;

In the parent class component we declare attribute binding with For eg., like this format in tag [inputData] to pass data.

 <posts [data]="posts"></posts>

Let us discuss this with the small example having parent class as parent.component.ts and child class as child.component.ts.

Step 1 – Create a new app using ng new app-name

But before performing this operation you should have installed angular CLI tools. Invoking this command in command prompt will create an angular app with default folder structure, which will help us to maintain a cleaner code.

Step 2 – Create a parent Component using ng g c parent

This will create a component with the html, stylesheet (scss, css, sass, less), typescript, spec(Unit testing). Repeat the same procedure for creating the child component as ng g c child

This will create a two directory parent and child like mentioned below:

Folder structure of parent and child

App Component is the starting point of angular application. In app.component.html we indicated a selector parent as

<app-parent></app-parent>

parent.component.ts

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

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
  parent: any;
  constructor() { }

  ngOnInit() {
    this.parent = 'Sample App';
  }
}

In parent.component.ts we have declared a variable of type any. And on component initialization on ngOnInit a typescript variable is assigned the value. In parent.component.html below

<app-child [data]="parent"></app-child>

In the above html code app-child refers to child component selector which we have given when creating component. Each component html page is identified by selector in component.ts file. [data] represent input attribute because some data needs to be inputted.

child.component.ts

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
// tslint:disable-next-line: no-input-rename
  @Input('data') data: any;
  constructor() { }

  ngOnInit() {
  }

}

Here in the above code, in the child.component.ts @Input refers to data to be based to child component.

<p>
  {{data}}
</p>

The above is child.component.html where data is passed to child which when displayed in html emit the assigned value. This is how we pass the data from the parent to child using @Input decorator.

Write a Reply or Comment

Your email address will not be published. Required fields are marked *

Comments (0)