AngularTutorials

Learn Angular Step by Step – Session 8 : Inter component communication

Welcome back.! . After discussing about angular directives here we are going to discuss about inter-component communication in angular. You may already know that components are the building blocks in angular and it is very important to communicate between them.

In this session we are discussing only about Inter-component communication in the same route or same view without complex methods like redux. We will discuss the communication between routes in the future routing lessons and Redux will be again another separate session.

Inter-component communication can be divided in to several areas

  1. Parent to child communication
  2. Child to parent communication
  3. Sibling communication

Before we demonstrate about these concepts I think it is better to make our folder structure more clear in our LibApp project. When you are developing a project you might want to change locations of the components to make the folder structure clear. So first lets do that and come back again to the topic.

For the moment we have the following folder structure.

What I am going to do here is I am going to create a new folder called components and there I will create new two folders called shared and views.

I will right click the app folder and select new folder. To make the sub folders you have to right click in the components folder. Now we have the following folder structure.

Since header and footer are shared components I will drag and drop those folders to shared folder. It will prompt a message asking are you sure. By pressing move you can move it.If the application is running this will break the application. Don’t worry we will be fix that issues in a moment. So after moving the header and footer to shared folder you can see the folder structure as below.

As you know all the components are imported in the app.module.ts folder we have to change the import paths there. So I will open it there I can see the paths are showing errors.

Now what I have to do is correct those relative paths. So I will add /components/shared in-front of /lib…

So the errors have been disappeared and if we run the application by “ng serve” it will work. There are several guild-lines on designing the project structure we will be discussing about them later. For the moment lets stick in to this.

Back to the topic. From the three types I have mentioned above lets talk about the parent to child communication

When we are using a component inside another component we may want to pass a value to child component to do some calculation or to show somewhere in the child component. To do this we are using Input() decorator.

In our application lets say we have a child component in the home view to show the number of books we have. So the book list array is in the home component and we want to pass the length of he array to child component. So lets create the component called bookCount inside the shared folder.

Here you can see when I type the component name first I got a spelling mistake. So I have pressed Ctrl+X suddenly and terminate the job and created the component with right spellings. If a wrong component has been created before terminate the job you can delete the component folder and remove imports in the app.modules.ts folder. This kind of information will help when you are practically working with angular.

Again back to the topic. Now we have BookCount component. First I will use it in app.component.html file. To find the element tag to import we want to go to the book-count.component.ts and copy the selector

Then I will paste in app.component.html file after book list heading as opening and closing elements.

Then I will go to book-count.component.ts file and create a new variable as bookCount: number

In the book-count.component.html file I will add the following statement.

<p *ngIf=”bookCount”>{{bookCount}} Books found</p>

From the knowledge gained from the previous lessons you know what is happening here. If there is a value of bookCount this will show a message with bookCount. For the moment we have only defined the variable and not assigned any value. So we have to pass a value from the parent component. Before that we can change the variable definition to accept a value from the parent.

@Input() bookCount: number;

To use the Input decorator you have to import the Input from @angular/core

Now this component can accept the values from parent component. So I will go to the parent component which is app.component.html file in this case and add a parameter called [bookCount] to the element definition.

What is happening here is setting the parsing the length of bookList as bookCount to the book Count component. Now our application is look like below.

Here we have used the variable name in the child component as a parameter in parent component element. If you want to change the parameter name to the variable name in the child you can defined a name inside Input(). For example you can say @Input(‘count’) bookCount: number. Then in the parent component you have to use ‘count’ as the parameter inside the element and value will be sent to child component’s bookCount variable. Now you know how to do parent to child communication and let’s now move on to child to parent component.

Child to parent communication

In some scenarios we need to communicate from the child component to parent component. Lets say there is a button in the child component when the button pressed change is happens in the parent component or when the user enter some text in a text box in child component but that text need to be send to the parent component. In such cases we have to output the event from the child component.

To demonstrate this Let’s add a button in the book-count.component.html file as refresh button and we will do some action in the parent component (app component) once it is pressed.

<button (click)="RefreshButtonClicked()">Refresh</button>

Here I have added a click event in the button. It will call the function when the button is clicked. So I have to write that function in ts file.

  RefreshButtonClicked() {
  }

Now what is left is to emit the click event to parent component. So I will create a event emitter object with output decorator.

 @Output() refreshContent= new EventEmitter<any>();

To use Output and EventEmitter you have to import them form @angular/core. If we discuss more about the above statement @Output is the decorator we are using to tell angular that we want to send this content to parent element. refreshContent is the eventEmitter name which we have to call in the parent component if we haven’t specify any other name in @Output(). Then the new word with EventEmitter to create a new EventEmitter component and <any> phase is used to specify the type of the data we are sending. Here I am sending the click event. So I have put “any” there. If you are sending string or number or any other data type you can specify the data type between <>. For the moment our component look like follows.

Now I will write a code inside RefreshButtonClicked() to emit a event.

 this.refreshContent.emit();

This is not specially passing the Click Event but it will trigger every time once the function is called. If we want to pass the extract click event you can send it from the html file as ($event) and emit it. If you want to pass string or number variable then you can send it as .emit(variable). We will do this kind of examples in the future.

Now in the parent component we have to catch that event. So in app.component.html file I’ll change the child element.

 <app-book-count *ngIf="bookList" [bookCount]="bookList.length" (refreshContent)="refreshContent()"></app-book-count>

(refreshContent) is the EventEmitter name we have used in the child component and refreshContent() is the method to be called when the event is emitted. if you have passed any variable in child component you can catch it by making refreshContent($event).( You can do this kind of value parsing. If you faced any issue use the comment section. I’ll help you.). Once the function is stated here we have to create the function in ts file. So I’ll open the app.component.ts file and add the function and to demonstrate the refresh like visual indication I will remove and add the book list with javascript timeout (Timeout will run the code inside it after 100ms).

Now if you go and check by clicking refresh button you will see like a refresh but this is not a actual refresh data call since we haven’t none any get or post requests up to now. We will do it in a future tutorial.

3. Sibling to Sibling communication.

This is happen when there are two child components in a parent component and need to pass a value from a child component to another child component. To pass data using @Input and @Output decorators you need to pass the value from child component to parent component and then emit that value to other child component in parent component. I am not going to do any example here since you have the idea by the above examples.

So in this session you have learned how to do inter-component communication and how to change the folder sturcture in a project. In the next session we will be learning Life Cycle Hooks in angular. Use the comment section if you have any comments and lets meet again with next session.

Comment here