To Start this article first we are going to create a fresh angular project by command, Angular CLI(Command line interface) make easier and fast to work with angular CLI project. To create a new Angular project use this command. Here my project name is "routing". after successfully create this app we are going to create some components. I am going to create some components home, employees and pageNotFound. To Create new components use this Command line. or Set "<basehref="/">" in index.php Best Practice for Routes Creates a new separate module by CLI command. The created file looks like this. Import the RouteModule into the src/app/app-routing.module.ts page. '@angular/router' is a route Package. Now define our routes to define our route creating a const "appRoutes", we know Route is an array and here Four Array object. Now let's understand the purpose of each of this object. First When the user calls the path something like "http://localhost:4200/home" so this path in the URL match with the first line of Routes. So, in this case, we want to display "HomeComponent" to view. The fourth Route is special route when the user request for unlisted routes in this above routes "PageNotFoundComponent" component will call. Next thing to do that let's angular know that where routes are defined. So make a forRoot method for imports. Specify where you want the route component view template to be displayed using the <router-outlet> directive. Edit app.component.html Now test your application manually in the browser. Ok Great, now Test for employees and see what happens. ng new routing
Create Components in angular CLI
ng generate component home
ng g c home
Step 1:
<base href="/">
Step 2:
ng generate module app-routing --flat --module=app
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
@NgModule({
imports: [
CommonModule
],
declarations: []
})
export class AppRoutingModule { }
import { RouterModule ,Routes } from '@angular/router';
const appRoutes:Routes= [
{path: 'home',component:HomeComponent},
{path: 'employees',component:EmployeesComponent},
{path: '' ,redirectTo:'/home',pathMatch:'fill'},
{path: '**',component:PageNotFoundComponent}
];
{path: 'home',component:HomeComponent},
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes)
],
Step 3:
<h1>{{title}}</h1>
<router-outlet></router-outlet>
<app-messages></app-messages>
About the author
Hello, My Name is Brijpal Sharma. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of Codermen. I started this blog to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers...
You must be logged in to post a comment.