Angular 2 Parent and Child Component Communication

Posted By : Avilash Choudhary | 05-Jan-2017

Angular 2 parent and child

There are many cases where we want parent and child communication.

 

Suppose parent component provides data to child component and when child component performs some action on that data it returns the result to parent component.

 

For that communication, Angular provides the Input and Output decorators.

 

Parent component provides the input and child component provides the output.

 

parent component.html

<div class="col-md-12 user-form-table overflowVisible">
        <div class="row">
            <div class="col-md-12">
                <div class="panel">
                    <div class="main_head">Search:
                        <span class="main_head_label">Enterprise using Enterprise Id or Name. </span>
                    </div>
                    <div class="panel-body search">
                        <ul class="padbot">
                           	 <dt-search (search)="searchEnterpriseData($event)" [enterpriseType]="'main'"></dt-search>             <!— this is the child component —>
			  </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

parent component.ts file will contain the method

searchEnterpriseData(data){

}


child component.ts file contains the 

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

@Component({
    selector: "dt-search",
    template: `this will render the html template`,
    styleUrls: [‘this will contains the css file path’]

})

export class SearchComponent {
    @Output() search: EventEmitter = new EventEmitter();     // this is the output decorator
    @Input("enterpriseType") private enterpriseType: string;				// this is the input decorator

}

enterpriseType input will contains the string main

 

To provide the output to parent component 

we have to call 

 this.search.emit(“some data”);  // this function will call the searchEnterpriseData method in parent component.
 

About Author

Author Image
Avilash Choudhary

Avilash has excellent experience in developing mobile and web applications using jQuery , Javascript and PhoneGap. His hobbies are watching and playing cricket.

Request for Proposal

Name is required

Comment is required

Sending message..