In this article, we will learn about routing and wildcard routes in Angular 6. We will learn from the beginning; i.e., how to set up an Angular 6 environment in VS Code.
Introduction
Routing is a mechanism to redirect the users from one page to another page. Angular Routing provides the navigation from one page to another page on which you want the user to redirect.
Prerequisites
- We should have a basic knowledge of HTML and JavaScript.
- Basic knowledge of TypeScript
- Visual Studio Code be installed
- Node and NPM installed
Integrated Development Environment
First of all, let's install NodeJS. Open this link for installing Node.js.
https://nodejs.org/en/download/
Download the latest version of Node.js according to the Windows version (64-bit or 32-bit) on your machine. To check the configuration of your machine, right-click on "My Computer", select Properties, and check the system type.
After downloading Node.js, intsall it and check the node and npm versions. To check the version, open command prompt, and type -
node -v
npm -v
After this, let us install Angular CLI. or installing Angular CLI, type the following command.
npm install -g @angular/cli
After installing CLI, create a new project including the routing using -
ng new Demoproject --routing
Open VS Code and open the Demoproject.
Now, open the integrated terminal by pressing Ctrl + and ~.
Let's add three components to your project with the names Home, About, and Contact.
- ng g c Home -it -is
- ng g c About -it -is
- ng g c Contact -it -is
- g for generate
- c for component
- -it for inline template
- -is for inline style
Now, check in the project if the component is created.
Now, let us configure the routes. For the configuration of the route, let us open App-routing.modules.ts and make the following changes in it.
- const routes: Routes = [
- {path:'Home',component:HomeComponent},
- {path:'About',component:AboutComponent},
- {path:'contact',component:ContactComponent}
- ];
Now, open App.component.html and add these lines of code.
- <nav>
- <a class="button" routerLink="/Home">Home</a>
- <a class="button" routerLink="/About">About</a>
- <a class="button" routerLink="/contact">Contact</a><br>
- </nav>
Now, add some style for the button in style.cs. Now open the integrated terminal and type
ng serve -o
This will run the project and you will get to see the browser window.
Check the result.
When we try to redirect a page which is not available, then we can redirect it to an Error page. Using the wildcard route, we can redirect to an error page if a particular page is not found.
We can use the Wildcard using "**"
In pat, Set path :"**" and set the component or view where we want to redirect in the case of the page not found condition.