Posted in .NetCore, Angular, Angular CLI, Angular5

Component Communication part 1

We know that all the Angular applications are made up of components; in fact components are the basic building blocks of Angular applications. In a simpler manner we can say component is UI/ Views element along with the mechanism to show an operate on data.

Angular Team defines component as the Patch of the screen that we call View which declares the reusable building blocks for an application. So, in short, component is anything which is visible to the eyes and which can be reused again and again.

Creating Components

As we are using the Angular CLI we can create the component in one command; if you don’t know how do this we set up the project using CLI. Please visit following link.

Angular Quick start with CLI

When you are done with the project setup now we are ready to add our new component by using the following command
In my case I will run command ng generate component myfirstcomponent ( This is the name of My component and you can choose your own ) this will generate the following folder structure in your application


Image1

When we create the component Angular CLI creates the folder with the name of the component and it adds the files myfirstcomponent. component.ts, myfirstcomponent. component.spec.ts, myfirstcomponent.component.html ,and myfirstcomponent.component.css files in the folder myfirstcomponent.

One more change that we can see is at the AppModule.ts .

import { BrowserModule } from ‘@angular/platform-browser’;

import { NgModule } from ‘@angular/core’;

import { AppComponent } from ‘./app.component’;

import { MyfirstcomponentComponent } from. / myfirstcomponent / myfirstcomponent.component ‘;

@NgModule({

declarations: [AppComponent,MyfirstcomponentComponent],

imports: [BrowserModule],

exports: [AppComponent],

providers: [],

bootstrap: [AppComponent]

})

export class AppModule {}

As we have One module so far in the application so whenever we add the component in the CLI it adds that component directly in the App Module which is the Root module of the application. It imports the component in the Root Module and adds into the declaration section which contains all the components present in the Module.

Exploring first component

When we look at our first component it adds the snippet like below

It’s an export of the component from the angular core which is needed to mark the class as a component

Next thing which we need to see are,

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

@Component({

selector: ‘app-myfirstcomponent’,

templateUrl: ‘./myfirstcomponent.component.html’,

styleUrls: [‘./myfirstcomponent.component.css’]

})

export class MyfirstcomponentComponent implements OnInit {

name: string = “John Doe”;

constructor() {}

ngOnInit() {}

}

Selector

It is a property which tells angular to create an insert of this component whenever it sees the element in the template

Templateurl

It is the URL of the html page which tells Angular what needs to be shown in the UI

So how does it work first Angular sees the selector for the component and it search the selector in the HTML and replaces the template/templateUrl which is rendered in that section. In our case the selector is app-myfirstcomponent and template is the myfirstcomponent.component.html which will be rendered in the Browser.

How to use this component ?

Ok we are done now to add and some basic stuff in View. To use this component we must keep in mind the selector property of the component which in our case is the app-component. To use this just add this line in the app.component.html so the code snippet for app.component.html will be like below

{title}

<app-myfirstcomponent></app-myfirstcomponent>


When we see the template URL it is like below for my product

hello {{name}} your first component works!


So, summing up we can say selector is the name of the component which will be used by the angular to call them inside the html

Passing Data Between Components

Ok we have seen how we create and consume the same component in the application now let’s see how we pass the between the components; as in most of the application we need to share the data between the components There are basically 4 Ways to pass the data between the components, let’s see them one by one.

Before that let’s see what we mean by parent and child component. Parent component is the component which acts as the container for other component and sibling is the component which is not container but which is not relatedImage2

Following are the ways we can pass the data between parent and child components, let’s see one by one

Parent Component to Child component.

There will be always a need that we should send the data between the parent component and child component to do this. Let’s see step by step how we can achieve this

@Input

This decorator which is present is used to obtain the data from the component. To achieve this I have made changes to the component. Let’s add two component namely master and child in the Application by using ng generate command of the Angular CLI

When the components are added look at the code snippet for the child component (child.component.ts)

  • import {  Component,   OnInit,  Input  } from ‘@angular/core’;
  • @Component({
  •     selector: ‘child’,
  •     templateUrl: ‘./child.component.html’,
  •     styleUrls: [‘./child.component.css’]
  • })
  • export class ChildComponent implements OnInit {
  •     @Input(“bindingmessaage”) message: string
  •     constructor() {}
  •     ngOnInit() {}  }

Here we have used the @Input decorator for making the message as input; let’s see the syntax of the @Input in detail. Here bindingmessage is present in @Input(bindingmessage) is used as the alias of the message property which can be used in the other components .

Ok so far we have made the message property of the ChildComponent for accepting the Values from the Parent component then how do we assign the values to this variable? For that purpose we must see the parent component (Remember this is Parentè Child interaction ). We must make the Provision in the parent component to set the values of this variable for that change, we must look at the snippet of the Master component

To that we must add the child component to the Master component — how do we do it ? We have selectors for our use here let’s look at the following html(Master.component.html) snippet

Master.component.html

  • <child bindingmessaage=”Message from the Parent Without Binding”>
  • </child>

 

app.component.html

  •     
  •         
  •     
  • </div>

  •  

    This code simply adds the master component in the App component which is our root component an master component in return adds the child component in its template When we run the application we can see the output as displayed at the start page .

    This is child component

    This is Message from parent:: Message from the Parent Without Binding

    Now to pass the value from the parent component to child component we have to the following changes

    Update the Master component (Master.component.ts) to following snippet

    • import {   Component,  OnInit } from ‘@angular/core’ };
    • @Component({
    •     selector: ‘master’,
    •     templateUrl: ‘./master.component.html’,
    •     styleUrls: [‘./master.component.css’]
    • })
    • export class MasterComponent implements OnInit {
    •     sendgreetingtochild: string = “Data from Parent to child using input decorator”;
    •     constructor() {}
    •     ngOnInit() {}
    • }

    And in the child template selector which is present in the master.component.html file as follows

    What we are doing here is we are assigning the value of the property sendgreetingtochild to the bindingmessage Input of the child component

    When we save the file, and see the output we can see the output as follows

    This is child component

    This is Message from parent:: Data from Parent to child using input decorator

    We can see the changed output which is the same where we have assigned the value of the variable in the master.component.ts

    To sum up this we can say that in order to pass the value from parent to child follow the below steps

    1. use @input to the properties which we want to assign the value
      @Input(“bindingmessaage”) message:string
    2. Use the property In the selector of the child component

    Passing Data between Child to parent (Using @Output) and Event Emitters

    We have seen how we can pass the data between then let’s see passing data between the component using @output an Event Emitters.

    In this the child component emits the data to the parent component by using the @output decorator an Event emitter this change can occur on button click or the any data change in between.

    To achieve this, we can do the  following things,

    1. Parent should have the provision to receive this message which will be assigned and used
    2. Child should have the variable decorated with @output and a function which will emit this event. And the message we want to send to the parent component.

    Let us add two component as follows using ng generate command,

    1. ChildwithoutputandemiterComponent.component.ts This will be our child component
    2. MasterwithoutputandeventemiterComponent.component.ts This will be our master component

    In order to see how we can use the @output an event emiters lets modify the child component with the following snippet

    • import {  Component,   OnInit,   Output,EventEmitter  } from ‘@angular/core’;
    • @Component({
    •     selector: ‘app-childwithoutputandemiter’,
    •     templateUrl: ‘./childwithoutputandemiter.component.html’,
    •     styleUrls: [‘./childwithoutputandemiter.component.css’]
    • })
    • export class ChildwithoutputandemiterComponent implements OnInit {
    •     message: string = “Hello from child”
    •     @Output(“messagefromchid”) emitmessage = new EventEmitter < string > ();
    •     EmitValue(): void {
    •         this.emitmessage.emit(this.Message)
    •     }
    •     constructor() {}
    •     ngOnInit() {}
    • }

    Before understanding the code let’s see some basic things we have in this snippet these are @output an the EventEmitter

    @Output

    It is the attribute which is used when we want to send the data outside the component

    This attribute always combined with the Event emitter which can be accessed outside the component . by using the Event passed.

    EventEmitters

    Event emitter is used in the Angular to emit events in the components.

    When we see the code description of the above code we can see that we have used the @Output attribute to the and we have set it to the new EventEmitter also we have method EmitValue which emits the Value of the Message Property to the master component .

    Next let’s see How does the Master component handle these values

    • import {   Component,  OnInit  } from ‘@angular/core’;
    • @Component({
    •     selector: ‘app-masterwithoutputandeventemiter’,
    •     templateUrl: ‘./masterwithoutputandeventemiter.component.html’,
    •     styleUrls: [‘./masterwithoutputandeventemiter.component.css’]
    • })
    • export class MasterwithoutputandeventemiterComponent implements OnInit {
    •     GreetingsFromChild: string = “Initial message at the master.”;
    •     receivemessage($event): string {
    •         this.GreetingsFromChild = $event;
    •         return this.GreetingsFromChild;
    •     }
    •     constructor() {}
    •     ngOnInit() {}
    • }

    In this what we have done is we have created the function Receive Message which receives the value from the Event emitter whenever change in the Variable occurs . In this function Receivemessafe($event) is the function which receives the value from the child component and assigning it to the messagefromchild of the

    To see the Output we have some change with the Child and Parent template let’s see one by One

    • <p>
    •    <b>Child component:: </b>
    •    <br>
    •       <input type=”text” [(ngModel)]=”message”>
    •       <button (click)=”EmitValue ()” value=”Emit Value”>Emit Value</button>
    •    <br>
    •    (click on Button to send the Value to Master component)
    • </p>

    This is the child template (html file) which has One input and we can see the EmitValue() from the Child component which will be called whenever the button clicks happen. Another change that we need to do is change at the master component like below

    • <p> <b> Master component :: </b> <br> <b> {{GreetingsFromChild}}</b> <br>
    •     <app-childwithoutputandemiter (messagefromchid)=receivemessage($event)></app-childwithoutputandemiter>
    • </p>

    When we look at the code we can see that we have added the child component inside the master component for receiving the output. What we have done is we have assigned the receivemessage($event) to the messagefromchild

    This was all about the passing of the data from the parent to the child an child to parent we will see the next methods by using the @viewchild and By using the services in next article
    Please run npm Install before Running this project
    References

    1. https://angular-2-training-book.rangle.io/handout/components/
    2. https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/#Parent-to-Child-Sharing-Data-via-Input
    3. https://angular.io/guide/quickstart

    Happy coding.