Sunday, October 29, 2023

Angular Routing with Parameters and how routing works

Route path can receive data from url with the help of parameter, this is
 similar to querystring concept of traditional web development

  http://../details.aspx?pid=p001----------->details.aspx
                                                  |
                                            Request.queryString["pid"]




Paraname should be prefixed with :,route path can have any numb of paras

Parameter value can be read with in component class using "ActivatedRoute" class

Syntax:
   this._activatedroute.ParamMap.subscribe((paras)=>{
                 paras.get("paraname")
                                                  });



How Angular Routing Works


angular router performs the following 7 steps

Step1: Parse the URL
Angular Router takes the browser URL and parses it as a URL tree. To parse the URL, the angular framework uses the following conventions:

  1. Slashes (/): slashes divides URL segments
  2. Parentheses (): Parentheses specify secondary routes
  3. Colon (:): A colon specifies a named router outlet.
  4. Semicolon (;): A semicolon specifies a matrix parameter
  5. Question Mark (?): A question mark separates the query string parameters.
  6. Hashtag (#): The hashtag specifies the fragment
  7. Double Slash (//): A double slash separates multiple secondary routes.

Step2: Redirect

Before Angular Router uses the URL tree to create a router state, it checks to see if any redirects should be applied. There are two kinds of redirect.

Local Redirect: When redirectTo does not start with a slash. Replaces a single URL segment. For example, {path:’one’, redirectTo:’two’}.

Absolute Redirect: When redirectTo starts with a slash, replaces the entire URL. For example, {path:’one’, redirectTo:’/two’}.

Step3: Identify the Router State

In this step, the Angular Router traverse the URL tree and matches the URL segments against the path configured in the Router Configuration. If a URL Segment matches the path of a route, the route’s child routes are matched against the remaining URL segments until all URL segments are matched. If no complete match is found, the router backtracks to find a match in the next sibling route.


Step4: Guard – run guards

At the moment, any user can navigate anywhere in the application. That’s not always the right thing to do. Perhaps the user is not authorized to navigate to the target component. May be the user must be login (authenticate) first. May be you should fetch some data before you display the target component.

ou might want to save pending changes before leaving a component. You might ask the user if its OK to discard pending changes rather than save them.

You can add guards to the route configuration to handle these scenarios.

Step5: Resolve

It resolves the required data for the router state.

Step6: Activate

It activates the Angular Components to display the page

Step7: Manage

Finally when the new router state has been displayed to the screen, Angular Router listens for URL changes and state changes. It manages navigation and repeats the process when a new URL is requested.


Wild Card Route in Angular(Handle Invalid URL )

 What is Wildcard Route in Angular?

The Wildcard Route is basically used in Angular Application to handle the invalid URLs. Whenever the user enter some invalid URL or if you have deleted some existing URL from your application, then by default 404 page not found error page is displayed. In such scenarios instead of showing the default error page, if you also show a custom error page and this is possible by using the Angular Wildcard Route.

How to use Wildcard Route in Angular?

A Wildcard route has a path consisting of two asterisks (**). It matches every URL, the router will select this route if it can’t match a route earlier in the configuration. A Wildcard Route can navigate to a custom component or can redirect to an existing route. The syntax to use Wildcard Route is given below

 {path:'**',component:InvalidComponent}


Example

Follow previous example first,



Next make the below changes to AppModule.ts




















Now, we need to create a Invalid Link, so on clicking on the invalid link it should redirect
to InvalidUrl Component.

.HTML Changes


<h2>https://dotnetbyudayrajakonda.blogspot.com/</h2>
<nav class="navbar navbar-inverse">
    <ul class="nav navbar-nav">
        <li>
            <a routerLink="home" routerLinkActive="active c1">Home</a>
        </li>
        <li>
            <a routerLink="about" routerLinkActive="active c1">About</a>
        </li>
        <li>
            <a routerLink="contact" routerLinkActive="active c1">Contact</a>
        </li>
        <li>
            <a routerLink="services" routerLinkActive="active c1">Services</a>
        </li>
        <li>
            <a routerLink = "invalidLink" routerLinkActive="active c1">Invalid Link</a>
        </li>
    </ul>
</nav>
<hr>
<router-outlet></router-outlet>
<h4 class="navbar-fixed-bottom">copyrights&copy; reserved to my blog</h4>
















Now, on clicking on the Invalid Link, it should redirect to customerrorcomponent
that is invalidcomponent













Note: If you add the Wildcard Route as the first route in Router Configuration then no other routes will be reached as the Wildcard Route always matched

Order of Routing 

The order of the routes is very important. When matching routes find, the angular router uses first-match wins strategy. So more specific routes should be placed above less specific routes. So, Routes with a static path should be placed first, followed by the empty path route, that matches the default route.

Redirecting Routes in Angular

When the application start, it navigates to the empty route by default. We can configure the router to redirect to a named route by default. So, a redirect route translates the initial relative URL (”) to the desired default path. 


For example, if you want to redirect to Login page or registration page by default when the application start. Then you need to configure the redirectTo

Syntax




Example


Create a Component






Continuation of Previous Example, 

https://dotnetbyudayrajakonda.blogspot.com/2023/10/routing-example-2.html


Add the below code in appModule.ts




The empty path in the first route represents the default path for the application. This default route redirects to the route for the /Login URL and therefore will display the Login Component

A redirect route requires a pathMatch property to tell the router how to match a URL to the path of a route. The router throws an error if you don’t. For the special case of an empty URL we also need to add the pathMatch: ‘full’ property so angular knows it should be matching exactly the empty string and not partially the empty string.

Instead of showing the default page when the URL is empty, we want to redirect to the Login page. This is where Redirecting Routes comes into picture in Angular Application.

Now, Run 












Routing Example 2

Create a below components

ng g c home

ng g c aboutus

ng g c contact

ng g c training

ng g c consultancy

ng g c services

ng g c invalid



 























Home Component. html






About Component.html






Contact Component.html










Training.html

<ul style="font-size:x-large">

    <li>Classroom Training</li>
    <li>Online Training</li>
    </ul>


Consultancy.html















Services.html


<div style="font-size:x-large;float:left">
    <a routerLink="training">Training</a> <br>
    <a routerLink="consultancy">Consultancy</a>
</div>
<div style="font-size:x-large;float:left;margin:15px">
    <router-outlet></router-outlet>
</div>


Invalid Component.html








App-Module. ts























Now, create a main page Component

ng g c mainpage --flat









.ts Changes












 styles: [".c1{background-color:'blue'!important}"]


.html Changes

<h2>https://dotnetbyudayrajakonda.blogspot.com/</h2>
<nav class="navbar navbar-inverse">
    <ul class="nav navbar-nav">
        <li>
            <a routerLink="home" routerLinkActive="active c1">Home</a>
        </li>
        <li>
            <a routerLink="about" routerLinkActive="active c1">About</a>
        </li>
        <li>
            <a routerLink="contact" routerLinkActive="active c1">Contact</a>
        </li>
        <li>
            <a routerLink="services" routerLinkActive="active c1">Services</a>
        </li>
    </ul>
</nav>
<hr>
<router-outlet></router-outlet>
<h4 class="navbar-fixed-bottom">copyrights&copy; reserved to my blog</h4>

Index.html













set MainpageComponent as bootstrap in appModule.ts






















Goto index.html to link bootstrap css cdn links
    ...
 <head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>



Now, Run 



















Note:
-----
Hyperlink click will verify router link path with routes collection, the matching
route path related component will be loaded dynamically into router-outlet
area of main page for presentation

Html5 is providing nav tag to create navigation bar

Bootstrap CSS is providing navbar and navbar-inverse css classes to
 apply shape and background color to navigation bar

Bootstrap css is providing nav and navbar-nav css classes to display
 ul li items as tabs and mouse over will highlight link with bright white color



Routerlinkactive is applying 2 css classes to selected link
  1.active-this is provided by bootstrap css to apply shape,backgroundcolor,..
           to selected link

  2.c1--this is custom css class created by developer,this will apply
        backgroundcolor blue to selected link,important option will
        overwrite backgroundcolor of active css class

*bootstrap css is providing navbar-fixed-bottom to arrange | display html element
 at the bottom of webpage[or browser window]


Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...