Pages

A Complete Guide To Angular Routing

Routing allows the user to create a single-page application into multiple views and allow navigation between them. We can switch to any view without changing its state or properties.

Steps to Route:

  • Create an Angular App

  • Create a two or more components to route using the following command:

ng g c component-name

  • Write the following code in app.component.html file

<h1>Routing tutorial in Angular</h1>


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

<br>

<a routerLink="about">About</a>

<br>

<a routerLink="user">User</a>


<router-outlet> </router-outlet>


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

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



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

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

import { AboutComponent } from './about/about.component';

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

import { UserComponent } from './user/user.component';

const routes: Routes = [

  {

    path : 'about',

    component : AboutComponent

  },

  {

    path : 'user',

    component : UserComponent

  },

  {

    path : '',

    component : HomeComponent

  },

];

@NgModule({

  imports: [RouterModule.forRoot(routes)],

  exports: [RouterModule]

})

export class AppRoutingModule { }


  • Add then simply import "AppRouting" module inside the app/module.ts file inside the @NgModule imports.

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

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


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

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

import { AngularPipeComponent } from './angular-pipe/angular-pipe.component';

import { UserComponent } from './user/user.component';

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

import { AboutComponent } from './about/about.component';


@NgModule({

  declarations: [

    AppComponent,

    AngularPipeComponent,

    UserComponent,

    HomeComponent,

    AboutComponent

  ],

  imports: [

    BrowserModule,

    AppRoutingModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }


Now, run the command using ng serve in CLI.

The output will be shown like this :

Click on the link and you will route to that view without loading a page.


No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...