8 Develop a single page application by using synchronous or asynchronous Angular routing.

 Develop a single page application by using synchronous or asynchronous Angular routing.


Step 1: Create a New Angular Project


ng new spa-routing-demo

cd spa-routing-demo

ng serve -o



Step 2: Generate Components

ng g c home

ng g c about

ng g c contact


Step 3: app-routing.module.ts

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

const routes: Routes = [
  { path: '', loadChildren: () => import('./home/home.module').then(m => m.HomeModule) },
  { path: 'about', loadChildren: () => import('./about/about.module').then(m => m.AboutModule) },
  { path: 'contact', loadChildren: () => import('./contact/contact.module').then(m => m.ContactModule) },
];

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


Step 4: app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent     // only this component
  ],
  imports: [
    BrowserModule,
    AppRoutingModule // routes handled here
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}   // <-- make sure this export line exists


Step 5: app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'spa-routing-demo';
}

Step 6:  app.component.html

<h1>{{ title | titlecase }}</h1>

<nav>
  <a routerLink="">Home</a> |
  <a routerLink="about">About</a> |
  <a routerLink="contact">Contact</a>
</nav>

<hr>

<!-- This is where routed components will appear -->
<router-outlet></router-outlet>

step: 7

ng g module home --route '' --module app.module
ng g module about --route about --module app.module
ng g module contact --route contact --module app.module

Step 8:  start service

ng serve -o

Comments

Popular posts from this blog

1. a. Angular Application Setup

2. Structural Directives - ngIf

Assignments - 1