Open In App

Routing in Angular 9/10

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.

Approach:



Syntax:

<li><a routerLink="/about" >About Us</a></li>
<router-outlet></router-outlet>
 { path: 'about', component: AboutComponent }

Example: We are going to create a simple angular application that uses angular routing. So first, we create an Angular app by running the below command in CLI.



ng new learn-routing

Then we are creating simple navigation that allows us to navigate between the different components, and we have created some components as well, so users can switch between these components using routing.




<span>
    <ul>
        <li><a routerLink="/" >Home</a></li>
        <li><a routerLink="/products" >Products</a></li>
        <li><a routerLink="/about" >About Us</a></li>
        <li><a routerLink="/contact" >Contact Us</a></li>
    </ul>
</span>
<router-outlet></router-outlet>

Here the router-outlet is routing functionality that is used by the router to mark wherein a template, a matched component should be inserted.

Then inside the app-routing.module.ts file, we have provided these routes and let the angular know about these routes.




import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home.component'
import { ProductComponent } from './product.component'
import { AboutComponent } from './about.component'
import { ContactComponent } from './contact.component'
  
const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'products', component: ProductComponent },
  { path: 'about', component: AboutComponent },
  { path: 'contact', component: ContactComponent, },
];
  
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: []
})
export class AppRoutingModule { }

And then simply import “AppRouting” module inside the app/module.ts file inside the @NgModule imports.




import { NgModule } from '@angular/core';
import { HomeComponent } from './home.component'
import { ProductComponent } from './product.component'
import { AboutComponent } from './about.component'
import { ContactComponent } from './contact.component'
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
  
@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    ProductComponent,
    AboutComponent,
    ContactComponent
  ],
  imports: [
    AppRoutingModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

So now run this using “ng serve” in CLI and open localhost://4200 in the browser here you see your navigation bar, and you can navigate from one component to another without page reload.

Output:


Article Tags :