Using the Router
Changing Routes / Views
Once all of the setup is done how do we actually change the route to get a different component view? There are 2 different ways we can do this one that will use HTML's anchor tag, <a> and the other that will use JavaScript, both have their uses.
prerequisites:
RouterLink
The Router Link is used when we want to change the route when the user clicks on link or button. In the below code when a user clicks on a link the proper component is loaded where you placed the <router-outlet></router-outlet>
Working Stackblitz Example
Programmatic Router Navigation
We can also navigate or change the view when something happens. For example, we get a successful login response or some other function is invoked we want to change the route. We can use Router Class from angular to change the page. Maybe after 5 seconds a new page is loaded
Using the Router.navigate
Line 1: Import the router into your component. This will give you access to the methods on Router
Working Stack Blitz Example
Key Point:
Navigating inside a function is very useful for cases when you need to change the view after something happens, like say login. We we wouldn't want a user to able to move into our app before we checked their email and password.
Last updated