15 April 2020

angular routing example

  • Open Command prompt and use below commands to create angular routing 
  • E:
  • cd E:\TestProjects\Angular
  • ng new angular-routing-example --style=scss --routing --skip-install
  • cd angular-routing-example
  • npm install
  • Open project in visual studio code
  • Create home, about, contact components under app folder in vs code.
  • Define Base URL (<base href="/">) in index.html page as below code.

  • <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>AngularRoutingExample</title>
      <base href="/">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="icon" type="image/x-icon" href="favicon.ico">
    </head>
    <body>
      <app-root></app-root>
    </body>
    </html>
    • Update app component as below
    <h1>Angular Routing Example</h1>

    <a routerLink="home">Home</a>
    &nbsp;&nbsp;
    <a routerLink="about">About</a>
    &nbsp;&nbsp;
    <a routerLink="contact">Contact</a>
    <div>
        <router-outlet></router-outlet>
    </div>
    • Update app-routing.module.ts file as below code
    import { NgModule } from '@angular/core';
    import { RoutesRouterModule } from '@angular/router';
    import {AboutComponentfrom './about/about.component';
    import {HomeComponentfrom './home/home.component';
    import {ContactComponentfrom './contact/contact.component';

    const routesRoutes = [
    {path:"about",component:AboutComponent},
    {path:"home",component:HomeComponent},
    {path:"contact",component:ContactComponent},
    {path:"",redirectTo:"home",pathMatch:"full"}
    ];

    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
    • import AppRoutingModule in app.module.ts as below code
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';

    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { HomeComponent } from './home/home.component';
    import { AboutComponent } from './about/about.component';
    import { ContactComponent } from './contact/contact.component';

    @NgModule({
       declarations: [
          AppComponent,
          HomeComponent,
          AboutComponent,
          ContactComponent
       ],
       imports: [
          BrowserModule,
          AppRoutingModule
       ],
       providers: [],
       bootstrap: [
          AppComponent
       ]
    })
    export class AppModule { }

    Output:



    No comments:

    Post a Comment