Angular

Posted in .NetCore

Blazor Application Bootstrap and Life Cycle methods

We have seen in last article how web assembly and C# can be a game changer and will help the C# to run on Browser so moving to next article let’s see how we can setup Blazor in your machine and how we can get started with our first application with Blazor

Agenda

  1. Environment setup
  2. Application Bootstrap Process
  3. Application Life Cycle Methods
  4. Conclusion

1.Enviornment Setup

While writing the this article the new experimental blazor framework 0.0.4 is been announced by microsoft To get this version there are few prerequisite as below

1.Install .Net Core SDK 2.1 from here

  1. Install VS 2017 Preview (15.7) with Web Work Bench selected while installation

3.Most important step is to install the language service extension for blazor from here

To verify the installation, Open the Visual studio and lets create one Asp.net Core web Application we will be able to see following templates

1

2.Getting Started and Building First Blazor App

We have done the setup part now it’s time to create our first demo app with Blazor how we can do this follow below steps

1.Create new Project with the Asp.net Core web Application selected Name it as BlazorDemoApp1 and Click Ok

2

 

  1. Next step is to select the Environment and using proper Template for the same

2.1 we Need to Make sure .Net Core is Selected Asp.net Core 2.0 or 2.1 as well is Selected for the same

2.2 Next step is to select the template for the Blazor application for our demo we will select the Template called Blazor and Press Ok

3

3.Application Bootstrap

Where does our application bootstraps? obviously it is the Main Method in the Program.cs how does it look lets look at the code snippet below

public class Program

{

static void Main(string[] args)

{

var serviceProvider = new BrowserServiceProvider(services =>

{

// Add any custom services here

});

 

new BrowserRenderer(serviceProvider).AddComponent<App>(“app”);

}

}

 

This is the place where we decide which component will be loaded in this the DOM element selector argument will decide whether we want to load the Root Component or not in our case the app element in the index.html will be used for the rendering

Main method can be used to add the various services which will be used for the DI in later part of the app

When we see the index.html snippet which is as follows

<!DOCTYPE html>

<html>

<head>

<meta charset=”utf-8″ />

<meta name=”viewport” content=”width=device-width”>

<title>WebApplication2</title>

<base href=”/” />

<link href=”css/bootstrap/bootstrap.min.css” rel=”stylesheet” />

<link href=”css/site.css” rel=”stylesheet” />

</head>

<body>

<app>Loading…</app> <!–Root Component Loads here–>

 

</body>

</html>

 

Here the Blazor-boot is used as the script type now question is why It is used here in the index.html

so when we build the application at that time the blazor-boot is replaced with the bootstrapping script which handles the .Net Run time and executes entry point of the application, following screenshot can tell us what is loaded at the place of the blazor-boot

4

Here we can see all the things needed to run the .net run time are loaded with this and our app gets bootstrapped

5

  1. Application Life Cycle methods

 

All right we have set up our project lets dig out the details of the Application life cycle method of the Blazor App. There are around 7 life cycle methods available in the Blazor app Blazor provides the Synchronous as well the asynchronous life cycle methods lets see one by one how they can be differentiated

There are mainly 7 Life cycle methods lets see all of them one by one

1.OnInit ()

This is the synchronous version of the application method which gets executed when the component gets Initialized, this gets executed when the component is completely loaded we can use this method to load data from services as after this method each control in the UI is loaded. This is executed when the component is ready and when it has received the values from the parent in render tree

  1. OnInitAsync ()

This is the asynchronous version of the application method which gets executed when the component is initialized, this is called when the component is completely initialized this can be used to call the data service or to load the data from the service. This is executed when the component is ready and when it has received the values from the parent in render tree

3.OnParametersSet ()

This is the synchronous way of setting the parameter when the component receives the parameter from its parent component, this is called when the Initialization of the component occurs

4.OnParametersSetAsync ()

This is Asynchronous way of setting the parameter when the component received the parameter from the parent component, this gets called when the initialization of the component occurs and i

5.ShouldRender ()

We use this method to suppress the refreshing of the UI if this method returns true then UI is refreshed otherwise changes are not sent to UI, one thing about ShouldRender () is it always does the initial rendering despite its return value

6.OnAfterRender ()

This is called each time when the component is done with the rendering all the references to the component are populated now, we can make use of this method to perform the additional steps like initializing the other components and all.

6.OnAfterRenderAsync ()

This method is asynchronous version of the  OnAfrerRender() which gets called when the rendering of all the references to the component are populated we can use this method to do additional initializing of the third party component.

Complete code demonstrating the Application life cycle is as follows

@page “/”

 

<h1>Application Life cycle Methods ..</h1>

@foreach (var item in EventType){  @item <hr />}

@functions{

 

List<string> EventType = new List<string>();

protected override void OnInit()

{

EventType.Add(” 1 OnInit”);

}

protected override async Task OnInitAsync()

{

 

EventType.Add(“2 OnInit Async”);

await Task.Delay(1000);

 

}

 

protected override void OnParametersSet()

{

EventType.Add(“3 On Parameter set “);

}

protected override async Task OnParametersSetAsync()

{

EventType.Add(” 4 OnParametersSet Async Started”);

await Task.Delay(1000);

 

}

 

protected override bool ShouldRender()

{

EventType.Add(” 5 Should render called”);

return true;

}

protected override void OnAfterRender()

{

EventType.Add(” 6 OnAfterRenderStarted”);

}

 

protected override  async Task OnAfterRenderAsync()

{

EventType.Add(” 7 OnAfterRender Async Started”);

await Task.Delay(1000);

 

}

}

Running above code we will get the output like below

6

We can see the steps and way it is been called one by one and the sequence of the application methods.

 

Conclusion

Blazor is the technology which uses the web assembly for running the application , It uses Asp.net core to build the application , It has many similarities with the current UI Framework languages like React or Angular and being a c# developer it will be a great platform to build the application specially single page application. Although not available for the production system but certainly exciting time Is ahead with this 😊

References

https://learn-blazor.com/getting-started/what-is-blazor/

https://blogs.msdn.microsoft.com/webdev/2018/03/22/get-started-building-net-web-apps-in-the-browser-with-blazor/

 

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.