Angular Routing allows for navigation between components and enables the changing of part of a page, hence the reasoning for developing single page applications. Routing uses the URL in the address bar to change components.
In this article, we are going to create a new Angular application and add components to implement Routing between the components.
Create a New Application/Add Routing To Existing Application
Create a new Application using Angular CLI:
ng new routing-example
When prompted, select Yes for angular routing. Or use the following command:
ng new routing-example --routing=true
To add routing to an existing application use the following command:
ng generate module app-routing --flat --module=app
For more information on setup, follow the steps mentioned here.
Adding New Components:
Add a new component using the following command:
ng generate component <component name>
For this demo, we need two components:
Adding new components will add the default classes in the component as well. In each component, we at least need the file types of the following: .html, .ts, .css, etc.
Adding Information and Routing:
Once components are added we need to add the route path and components to the app-routing.module.ts:
Add components on the main html page and map them using routerLink. To learn more about RouterLink and ActivatedRoute, click here.
In the languages.component.ts file:
We have created a list of Languages for the drop down. Actual Routing will happen when the
getInfo() method is called with the selected language. Once
router.navigate is called, the info route will be invoked and the language will be passed along the route.
In init, as the component loads, the value passed in
router.navigate is assigned to a variable and the information for the selected language is displayed on the screen.
Running the Application
- To run any Angular application, open the terminal on the IDE or Git Bash command prompt.
- [Optional]Run command—
- After the application dependences are up to date, run the application using the command
- Once the application starts on the default port 4200, run the address from any browser:
And you have successfully routed two different angular components! Add and customize the application to build on the model. The code for the above demo is available here.
The browser used for this tutorial is FireFox.