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:

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>

Keypoint: Router Link is used when changing the view on click.

<ul class="nav navbar-nav">
  <li>
    <a routerLink="about">About</a>
  </li>
  <li>
    <a routerLink="l">Services</a>
  </li>
</ul>

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

Keypoint: We can use the Router Class to change the route.

Using the Router.navigate

some.component.ts
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class someComponent{
}

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