Setting up routing in an Angular application
We will kick off our project by creating a new Angular application from scratch. Execute the following command of the Angular CLI in a terminal window to create a new Angular application:
ng new my-blog --routing --style=scss
We use the ng new command to create a new Angular application, passing the following options:
my-blog: The name of the Angular application that we want to create. The Angular CLI will create amy-blogfolder in the path where we execute the command.Important Note
Every command that we run in the terminal window should be run inside this folder.
--routing: Enables routing in the Angular application.--style=scss: Configures the Angular application to use the SCSS stylesheet format when working with CSS styles.
When we enable routing in an Angular application, the Angular CLI imports several artifacts from the @angular/router npm package in our application:
- It creates the
app-routing.module.tsfile, which is the main routing module of our application:import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; const routes: Routes = []; @NgModule({ Â Â imports: [RouterModule.forRoot(routes)], Â Â exports: [RouterModule] }) export class AppRoutingModule { } - It imports
AppRoutingModuleinto the main module of our application,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   ],   imports: [     BrowserModule,     AppRoutingModule   ],   providers: [],   bootstrap: [AppComponent] }) export class AppModule { }
We configured our application to use the SCSS stylesheet format. Instead of creating the styles of our application manually, we will use the Bootstrap CSS library:
- Execute the following command in a terminal window to install Bootstrap:
npm install bootstrap
We use the
npmexecutable to install thebootstrappackage from the npm registry in the previous command. - Add the following
importstatement at the top of thestyles.scssfile that exists in thesrcfolder of our Angular application:@import "~bootstrap/scss/bootstrap";
The
styles.scssfile contains CSS styles that are applied globally in our application. In the previous snippet, we import all the styles from the Bootstrap library into our application. The@importCSS rule accepts the absolute path of thebootstrap.scssfile as an option, without adding the.scssextension. The~character represents thenode_modulesfolder of our Angular application.Important Note
The
node_modulesfolder contains all the npm packages and libraries that our application needs, either during development or runtime.
In the following section, we will learn how to create the basic layout of our blog by creating components, such as the header and the footer.