Angular 2 Parent and Child Component Communication
Posted By : Avilash Choudhary | 05-Jan-2017
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.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Avilash Choudhary
Avilash has excellent experience in developing mobile and web applications using jQuery , Javascript and PhoneGap. His hobbies are watching and playing cricket.