Sunday, 25 November 2018

Routing and navigation in Angular

Background

This post is in continuation of previous two posts on Angular -
In this post, we will see how we can set up routing and navigation in Angular. If you are new to Angular please read the Hello World go through the posts above first. This post assumes you have a base project already setup as we did in the last post.

Our current angular project looks something like below -




Routing and navigation in Angular

Before we start adding routing and navigation let's add a new component first and then we would add routing to that component. To generate a new component we can use the following command -
  • ng generate component <component-name>
In our case, we will create a new component called new-employee and we will put it under a directory called employee. So use the following command -
  • ng generate component employee/new-employee 



You can see it creates/updates following files -
  • CREATE src/app/employee/new-employee/new-employee.component.css (0 bytes)
  • CREATE src/app/employee/new-employee/new-employee.component.html (31 bytes)
  • CREATE src/app/employee/new-employee/new-employee.component.spec.ts (664 bytes)
  • CREATE src/app/employee/new-employee/new-employee.component.ts (292 bytes)
  • UPDATE src/app/app.module.ts 

Let's try to understand what each file is -
  • new-employee.component.ts : Components typescript file
  • new-employee.component.html : Components HTML file
  • new-employee.component.css:  Components CSS file
  • new-employee.component.spec.ts : File corresponding to the test for the component
  • src/app/app.module.ts : New Component is added to imports and declaration in the main module file.
Now that we have generated our new component let's add some HTML for it. Notice it is similar to the root component in terms of file and structure. Root component is used to render the main page and all the remaining component can be rendered/navigated through the main component. Root component is always added in the bootstrap property of the main angular module. In our case it is AppComponent. Our code and directory structure should look like below -


Now let's add some code to our new component. First, we will add some variables that we can dynamically set and bind in our HTML file. So go in the components typescript file (new-employee.component.ts) and add name and age as variables. In the ngOnInit method, initialize these to the values you want. So the typescript file looks like below -


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

@Component({
  selector: 'app-new-employee',
  templateUrl: './new-employee.component.html',
  styleUrls: ['./new-employee.component.css']
})

export class NewEmployeeComponent implements OnInit {

  name: string;
  age: number;
  constructor() { }
  ngOnInit() {
    this.name = "Aniket";
    this.age = 27;
  }
}

Now let's write the corresponding HTML file (new-employee.component.html). Remove any existing code that might be present there and add below code -

<h1>Welcome to the Employee portal</h1>


<h3>Name : {{name}}</h3>
<h3>Age : {{age}}</h3>

Notice how we are binding name and age variables from our typescript file. You can possibly change this values on events and the changes should immediately reflect in the rendered page.


Now that we have our components HTML and typescript file ready let's do our navigation setup. Note you can also add your custom CSS in new-employee.component.css. To add navigation we will make changes in app-routing.module.ts file.

If you remember our first tutorial we when we created our angular app we said setup routing to yes. This should create an app-routing.module.ts file for you. This should already have the boilerplate code for routing like importing router modules and exporting the module itself so that it can be imported into our main module. Make changes to this file so that it looks like below -

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {NewEmployeeComponent} from './employee/new-employee/new-employee.component'

const routes: Routes = [
  { path: 'newemployee', component: NewEmployeeComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule { }


Here we have imported our new component. That's line -
  • import {NewEmployeeComponent} from './employee/new-employee/new-employee.component'
Then we have added a route for this component in the empty array the boilerplate code had. This essentially says if anyone tried to access the "/newemployee" path then use the NewEmployeeComponent and render it to the router outlet. We will come to router outlets in a moment. 

So that's the two changes we have done. Now go back to app.module.ts and verify that 
  1. NewEmployeeComponent is imported and added to the declaration section.  
  2. AppRoutingModule is imported and added to the imports section
Once you have verified this, we have one last thing to do - add router outlet. Before I proceed let me summarize the angular bootstrap process that happens. We know our configuration is in the angular.json file which points to our main file main.ts that essentially bootstraps our main module app.component.ts. The main module will try to load the root component app.component.ts that has selector app-root by default. This selector is used in our main index.html page which us again configurable from angular.json. You can also notice that default index.html file has the tag   <app-root></app-root> in the body which is where our root component renders. You would also see that AppComponent which is our root component is listed in the bootstrap property in the main module. 


As you must have already been wondering there is no routing support added so far. And that is correct. We need to tell angular where the component should render. And for this, we use a special tag called -
  • <router-outlet></router-outlet>
So let's add this in our root component HTML file. So go to app.component.html and make changes so that it looks like below -


<div class="hello-world">
  <h1>Hello World!</h1>

  <p>----------</p>
  <h1>Routed modules go below</h1>
  <p>----------</p>
  <router-outlet></router-outlet>
  <p>----------</p>
</div>


Notice that <router-outlet></router-outlet> tag I have added. This is where our new component would get rendered. Now go to the app in the command line and execute -
  • ng serve -o
You should see below the screen when you navigate to -

  • http://localhost:4200/newemployee

You can see how our new component got rendered inside our root component. Root component generally has the layout design and based on users navigation we can render the custom component. We will continue to see more angular concepts in upcoming posts. So stay tuned!




Related Links

No comments:

Post a Comment

t> UA-39527780-1 back to top