Programmatical routing
- βοΈTrigger the route programmaticallyLearn how to trigger a route programmatically in an Angular application.
In the last step, you tested the form with this scenario:
- Click on the
Add a new task
link - Enter a title and a description in the form
- Click on the
Create task
button - Click on the
List of tasks
link
But what if you want to redirect the user to the list of tasks after the form is submitted? Thatβs a common scenario in web applications, and Angular provides a way to do that.
You saw how to trigger a navigation by clicking on a link with the routerLink directive. But in our situation, you want to trigger a navigation when the createTask function is called.
Inject the Router
Your TaskService service is not the only element you can inject in the constructor of a component. By using the Angular Router feature, you can inject the Router service in a component.
This service provides information about the current route and allows you to navigate to a different one.
π Instructions
-
Update the
src/app/task-form.component.ts
file.
The navigate function expects an array of route segments as a parameter.
In our case, you want to navigate to the tasks
route as you defined it in our route definition, so you use ['/']
;
Letβs test it out
Now if you repeat the previous scenario:
- Click on the
Add a new task
link - Enter a title and a description in the form
- Click on the
Create task
button
You should be redirected to the list of tasks.
βοΈ What you learned
In this chapter, you learned how to use programmatical routing in an Angular application. You learned how to inject the Router
service in a component and use its navigate
function to navigate to a different route.