Tuesday, October 17, 2017

Communicate with parent and child component in Angular.

In this article we will be discussing about communicating between child and parent component in Angular. $scope and $rootScope concepts are removed in Angular, and this is one of the reason for improved performance in Angular application.

1. Share data from parent to child component.
2. Share data from child to parent component.
3. Invoke a function in the parent component from child component.
4. Invoke a function in the child component from parent component.

Let us create a parent and child component first.

Parent component


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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title : string;
  constructor(){
    this.title = 'Parent child communication';
  }
}

./app.component.html


<child-component></child-component>

Child component


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

@Component({
  selector: 'child-component',
  template: '<div>'
      +'<span>Child Component: </span>'
    +'</div>',
  styleUrls: ['./app.component.css']
})
export class ChildComponent {
 constructor(){}
}

Module code


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import {ChildComponent} from './childComponent';

@NgModule({
  declarations: [
    AppComponent,ChildComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

We are done with our simple parent and child component. Now let us check how we can communicate with each other. Let us check the scenarios one by one.

1. Share data from parent to child component


Let us check with a simple example.

Updated parent component html


<child-component name="Angular"></child-component>

Updated child component to receive data


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

@Component({
  selector: 'child-component',
  template: '<div>'
      +'<span>Child Component: </span>'
      +'<span>{{name}}</span>'
    +'</div>',
  styleUrls: ['./app.component.css']
})
export class ChildComponent {
 @Input() name: string;
 constructor(){}
}

Here we have used @Input and the same we have imported as dependency as well. Above example we are passing a string directly, you can assign that into your component and pass as well. For that there will be small change, check below code for that.


Binding a variable in the parent scope

<child-component [name]="name"></child-component>
//name you can declare in your parent component
//same for array and object as well

Binding a string in the parent scope

<child-component name="Angular"></child-component>

Same way you can pass array or object as well. If you want to check with another example check this link as well, here basically explaining about a reusable component but using same concept.

2. Share data from child to parent component.


Above we have explained about sharing data from parent to child component, now let us check how we can share data from child to parent.

Child component


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

@Component({
  selector: 'child-component',
  template: '<div>'
      +'<span>Child Component: </span>'
      +'<span>{{name}}</span>'
      +'<button (click)="shareData()">Share data to parent</button>'
    +'</div>',
  styleUrls: ['./app.component.css']
})
export class ChildComponent {
 
 @Input() name: string;
 @Output() shareDataToParent = new EventEmitter();
 
 title : string;
 constructor(){
     this.title = 'Sharing from child to parent';
 }
 
 shareData(){
     this.shareDataToParent.emit(this.title);
 }
}

Dont forget to import Output and EventEmitter. Here we are emitting the data and this should be passed to our parent component, for that check below updated parent component html.


<child-component name="Angular" (shareDataToParent) = shareDataToParent($event)>
</child-component>

You can access this shareDataToParent method in your parent component.

Parent component


shareDataToParent(sharedText:string){
  console.log(sharedText);
}

We are done, click on the button you can see the data printing in the console. I have created a simple rating star component using the same concept, check that as well for better understanding the real time usage.

3. Invoke a function in the parent component from child component.


Basically you can use the same approach what we discussed above to access parent methods. Another approach is to inject the parent component in the child one, but I suggest to use above mentioned approach. So I am not repeating the same here.

4. Invoke a function in the child component from parent component.


Let us check how we can invoke a method in the child component from parent. Here we don’t required any changes in parent component except we need to update html code. Check below updated code.

Updated html code


<child-component #invokeChild></child-component>
<button (click)="invokeChild.invokeChildMethod()">Access child method</button>

Updated child component


invokeChildMethod(){
     console.log('Click triggered from parent component');
 }

Here also no changes except we just added the same method. Click on the button in the parent component you can see your child component method is getting triggered.

And also you can communicate between components using a service file as well, check that as well for better idea. In this article we have discussed about communicating between parent and child components also accessing the methods in each component. Hope you enjoyed this article.

Related Info

1. How to show a date is today or yesterday or last week etc using pipe - Angular

2. Disable submit button until all mandatory fields are filled - Angular

3. Angular client side pagination.

4. Angular show more/less pagination

No comments :

Post a Comment