Angular Forms with Routing

 Angular Forms with Routing

Routing

Routing in Angular allows the users to create a single page application with multiple views and allows navigation between them. Users can switch between these views without losing the application state and properties. Routing lets users display specific views of their application depending on the URL path. As users perform application tasks, they need to move between the different views that you have defined. To handle the navigation from one view to the next you use the Angular Router. The router enables navigation by interpreting a browser URL as an instruction to change the view. To add this functionality to your sample application, you need to update the app.module.ts file to use the module RouterModule. Use can import this module from @angular/router.

v  Angular Router:

The router is a separate module in Angular. It is in its own library package, @angular/router. The Angular router provides the necessary service providers and directives for navigating through application views.

Using Angular Router you can;

ü  Navigate to a specific view by typing a URL in the address bar

ü  Pass optional parameters (query parameters) to the view

ü  Bind the clickable elements to the view and load the view when the user performs application tasks.

ü  Handles back and forward buttons of the browser

ü  Allows you to load the view dynamically

ü  Protect the routes from unauthorized users using Route Guards

v  Understand the Routing:

Angular Form Routing


v  Components of Angular Router:

1.      Router:

An Angular router is a service that enables navigation from one component to the next component as users perform application tasks like clicking on menus links, and buttons or clicking on the back / forward button on the browser. We can access the router object and use its methods like navigate() or navigateByUrl(), to navigate to a route.

2.      Route:

Route tells the angular router which view to display when a user clicks a link or pastes a URL into the browser address bar. Every route consists of a path and a component it mapped to. The router object parses and builds the final URL using the route.

Note: Route v/s Path- Route is an object that provides information about which component maps to a specific path. Path is a string that specifies where exactly the resource you want to access is located.

3.      Routes:

Routes is an array of route objects our application supports

4.      RouterOutlet:

The RouterOutlet is a directive <router-outlet> that serves as a placeholder, where the router should display the view.

5.      RouterLink:

The RouterLink is a directive that binds the HTML element to a Route. Clicking on the HTML element, which is bound to a RouterLink, will result in navigation to the route. The RouterLink may contain parameters to be passed to the route’s component.

6.      RouterLikActive:

RouterLinkActive is a directive for adding or removing classes from HTML element that is bound to a RouterLink. Using this directive, we can toggle CSS classes for active RouterLinks based on the current RouterState.

7.      ActivatedRoute:

The ActivatedRoute is an object that represents the currently avtivated route associated with the loaded Component.

8.      RouterState:

The current state of the router includes a tree of the currently activated routes together with convenience methods for traversing the router tree.

9.      RouteLink Parameters array:

The parameters or arguments to the Route. It is an array that you can bind to RouterLink directive or pass it as an argument to the Router.navigate() method.

v  Navigating to Router Links:

Angular provides extensive navigation functions for simple scenes that are too complex. Defining navigation items and corresponding views is called routing. Routing allows the users to create a Single Page Application with multiple views and allows navigation between them. Users can switch between these views without losing the application state and properties. Angular provides a separate router module for adjusting in the application. The task is to enable routing between angular components by making their routes when a user clicks the link. It will be navigated to page link corresponding to the required component.          

Steps:

1.      Create an Angular App.

    Ng new Route_demo

2.      For routing you will need components. Here, two components to display the registration and home page.

    ng generate component Home

    ng generate component registration

3.      In app.module.ts, import RouterModule from @angular/router.

Import {RouterModule} from ‘@angular/router’;

    Then in imports of app.module.ts define the paths.

    imports: [

    BrowserModule,

    AppRoutingModule,

    RouterModule.forRoot([

      { path: 'home', component: HomeComponent },

      { path: 'registration', component:RegistrationComponent }

    ])

      ],

4.Now for HTML part, define the HTML for app.component.html. In link, define routerLink’s path as the component name.

    <a routerLink="/home">Home </a><br>

    <a routerLink="/registration">Registration</a>

5. Apply router-outlet for your application in app.component.html. The routed views render in     the <router-outlet>

    <router-outlet></router-outlet>

6.      Now, just define HTML for home.component.html and registration.component.html

7.      Angular web-app is ready to execute.

File: App.mudule.ts:

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

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

import { RouterModule } from '@angular/router';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

import { HomeComponent } from './home/home.component';

import { RegistrationComponent } from './registration/registration.component';

 

@NgModule({

declarations: [

      AppComponent,

      HomeComponent,

      RegistrationComponent

],

imports: [

      BrowserModule,

      AppRoutingModule,

      RouterModule.forRoot([

      { path: 'home', component: HomeComponent },

      { path: 'registration', component:RegistrationComponent }

      ])

],

providers: [],

bootstrap: [AppComponent]

})

export class AppModule { }

File: app.component.html

    <a routerLink="/home">Home </a><br>

    <a routerLink="/registration">Registration</a>

    <router-outlet></router-outlet>

File: home.component.html

    <h1>Home</h1>

File: registration.component.html

    <h1> Registration Form </h1>

Type ng serve and you will get the output.

 

v  How does router Navigate work?:

    router.navigate()method is used to navigate to a specific URL programmatically. The navigate()method takes two arguments: the path to navigate and the route parameter value to pass.

v  Difference routerlink and navigate:

RouterLink- when applied to an element in a template, makes that element a link that initiates navigation to a route. Navigation opens one or more routed components in one or more <router-outlet> locations on the page.

v  Styling Active Router Links:

Styling the active router link in angular allows the user to differentiate between the active router link and inactive router links. Angular provides a special mechanism to work with active router links. 

Approach: 

·         Create the Angular app to be used.

·         Create the header component that contains the navigation links.

·         Then apply the “routerLinkActive” on each router link and provide the CSS class to this property. Here we have created the “active” class in CSS file.

·         Provide the { exact : true } to the root route to avoid multiple active router links.

Syntax:

    <a routerLink="/" routerLinkActive="active" >Home</a>

Here, I create one header component for active routerlink

File: header.component.html

<span>

            <ul>

                        <li><a routerLink="/" routerLinkActive="active">

                                    Home

                        </a></li>

                        <li><a routerLink="/products"

                                    routerLinkActive="active">Products

                        </a></li>

                        <li><a routerLink="/about"

                                    routerLinkActive="active">About Us

                        </a></li>

                        <li><a routerLink="/contact"

                                    routerLinkActive="active">Contact Us

                        </a></li>

            </ul>

</span>

<router-outlet></router-outlet>

Here we have provided the routerLinkActive which is routing functionality that automatically activate the current route, and we have to provide the CSS class as well. Here in routerLinkActive = “active” active is a CSS class that automatically applied to the activated route.

But here, it still causes an issue our Home route is always active even we navigate to some other route the reason behind this is the way routerLinkActive works. The home route workson “localhost:4200/” andotherroutesare “localhost:4200/about” so “routerLinkActive” finds “localhost:4200/” inside every other route and the Home router link is always active to deal with this angular provide another directive called routerLinkActiveOptions.

<span>

            <ul>

                        <li><a routerLink="/" routerLinkActive="active"

                                    [routerLinkActiveOptions]={exact:true}>Home

                        </a></li>

                        <li><a routerLink="/products"

                                    routerLinkActive="active">Products

                        </a></li>

                        <li><a routerLink="/about"

                                    routerLinkActive="active">About Us

                        </a></li>

                        <li><a routerLink="/contact"

                                    routerLinkActive="active">Contact Us

                        </a></li>

            </ul>

</span>

<router-outlet></router-outlet>

v  v  Navigating Dynamically:

When user want to explore the effect of adding routing in to the current application for e.g. Enter the root URL for the application (http://localhost:4200) and then click the Create New Product button. When you clicked the button, the Angular routing system changed the URL that the browser displays to this:

http://localhost:4200/form/create

If you watch the output from the development HTTP server during the transition, you will notice that no requests are received by the server for new content. This change is done entirely within the Angular application and does not produce any new HTTP requests. The new URL is processed by the Angular routing system, which is able to match the new URL to this

route from the app.routing.ts file.

...

{ path: "form/create", component: FormComponent },

...

v  Passing and fetching route parameters:

We know how to define routing and navigate to route with required parameters - now it’s time to receive data and use it. Following our example of component that displays a profile. We are going to receive the profile id passed through routing as a required parameter and get the complete profile object, based on that id.

We can assume at this point, that in the application we have a service that handles fetching profile data for us, based on the provided id. So the only thing we need to do is to invoke the method with the correct id.

Params related to the route of a component are stored in the ActivatedRoute object, that we can inject and use in our components. So for the following route definition:

const routes: Routes = [{ path: "profile/:id", component: ProfileComponent }];

There is a couple of ways to get the required parameter id from the ActivatedRoute:

·         params property - to get Observable of the required properties scoped to the route

this.route.params.subscribe(...);

·         paramsMap property - to get Observable that contains a map of the properties

this.route.paramMap.subscribe(...);

·         snapshot property - to access the current route snapshot and get static values, instead of the Observable (both params and paramsMap can be used)

this.route.snapshot.paramMap...

this.route.snapshot.params...

I will use the Observable with a Map. So in order to receive the id parameter in the component we simply have to get it from the paramMap, like this:

@Component({...})

export class ProfileComponent implements OnInit {

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {

    this.route.paramMap.subscribe((params) => {

      const id = params.get('id');

    });

  }

The map has two useful methods available for us:

  • has(parameterName) - which checks whether the map contains a given parameter
  • get(parameterName) - which retrieves the parameter value

Now we can use the id to get complete profile data using some service. The exact implementation may vary depending on your specific needs, and it can look for instance as follows:

@Component({...})

export class ProfileComponent implements OnInit {

profile;

  constructor(

    private route: ActivatedRoute,

    private profile: ProfileService,

  ) {

  }

 ngOnInit(): void {

    this.route.paramMap.subscribe((params) => {

      const id = params.get('id');

      this.profile = this.profiles.getPerson(id);

    });

  }

We can then use the profile property of the component to display data in the template.

v  Query Parameters:

Reading query params works in the very same way as with required parameters - we just have to use a different set of properties to access the data. We can use:

·         queryParams property - to get Observable of the query params shared by all routes

this.route.queryParams.subscribe(...);

 ·         queryParamMap property - to get Observable that contains a map of the query params

this.route.queryParamMap.subscribe(...);

 ·         snapshot property - to access the current route snapshot and get static values, instead of the Observable (both queryParams and queryParamMap can be used)

this.route.snapshot.queryParams...

 this.route.snapshot.queryParamMap...

 

Post a Comment

0 Comments