Routing And Navigation on Command Line in Angular 6

| By Webner

Routing And Navigation On Command Line in Angular 6

Angular CLI tool can be installed with npm. It requires NodeJs.

We can download node from the official site [link] and install using instructions on the site.

node -v // this command is used to check the version of node js
npm -v // this command is used to check the version of NpM

Task Command
Install CLI npm install -g @angular/cli
Create app ng new my-angular-app
Switch to app folder cd my-angular-app
Add css ng new my-new-project –style=scss –routing
Start the app ng serve –open
View app in the browser http://localhost:4200

Now this is our basic and default app structure. After that we can create component and menu like : home, about, contact with this command line:

For example creating home page require this command:
ng generate component home and short form (ng g c home) then press enter.

// this command is used to generate new components and its view pages

New generated files are:-

CREATE src/app/home/home.component.css
CREATE src/app/home/home.component.html
CREATE src/app/homet/home.component.spec.ts
CREATE src/app/home/home.component.ts
UPDATE src/app/app.module.ts

It will update the app.module.ts to add this line in the top

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

Other menus can be created similarly.

Now you can start Routing process for components:

Routing is used for application to become a Single Page Application. If we want to reload different page on different link without reloading the entire application then we need to use routing feature.

This code need to add in the app.module file.

import { RouterModule, Routes } from '@angular/router'; 
// This will import the RouterModule and Routes from @angular/router

const appRoutes: Routes = [
  { path: 'home', component: HomeComponent },
];  //This route links the /'home' path to the Home Component so when /home is visited the router  will render the home component.

Add this code in the view main file.

<li class="nav-item"  routerLinkActive="active">
<a class="nav-link" routerLink="/home">home</a>

It will create a link named home, When we click on this link It will load the data from home view page and use the Home Component without reload the complete page.

routerLinkActive="active" is used for active menu link.
routerLink="/home" is used for redirect for component path.

This is third and main part of routing is setting router outlet.

Open your app.component.html or you can create separate component for navigation menu. And add <router-outlet></router-outlet> code under the menu code. So that the functionality will get activated automatically.
This is basic code for Routing and navigation in Angular6.

Leave a Reply

Your email address will not be published. Required fields are marked *