Codementor Events

Routing in Angular

Published Oct 18, 2020Last updated Apr 15, 2021
Routing in Angular

Routing

Angular Router is a powerful JavaScript router built and maintained by the Angular core team that can be installed from the @angular/router package. It provides a complete routing library with the possibility to have multiple router outlets, different path matching strategies, easy access to route parameters and route guards to protect components from unauthorized access.

The Angular router is a core part of the Angular platform. It enables developers to build Single Page Applications with multiple views and allow navigation between these views.

Router-Outlet

The Router-Outlet is a directive that’s available from the router library where the Router inserts the component that gets matched based on the current browser’s URL. You can add multiple outlets in your Angular application which enables you to implement advanced routing scenarios.

<router-outlet></router-outlet>

For clear underastanding create one angular project:

ng new Routing

create one component

ng g c Logincomponent

Path and Componet

The path refers to the part of the URL that determines a unique view that should be displayed, and component refers to the Angular component that needs to be associated with a path. the Router is able to navigate the user to a specific view.

Each Route maps a URL path to a component.

The path can be empty which denotes the default path of an application and it’s usually the start of the application.

The path can take a wildcard string (**). The router will select this route if the requested URL doesn’t match any paths for the defined routes. This can be used for displaying a “Not Found page” view or redirecting to a specific view if no match is found.

This is an example of a route:

{ path: ' ', component: LoginComponent' }
{ path:  'login', component:  LoginComponent}
{ path: '**', component: LoginComponent }

Could be also written as:

{ path:  'login',pathMatch: 'prefix', component:  LoginComponent}

The patchMath attribute specifies the matching strategy. In this case, it’s prefix which is the default.

The second  matching strategy is full. When it’s specified for a route, the router will check if the the path is exactly equal to the path of the current browser’s URL:

{ path:  'login',pathMatch: 'full', component:  LoginComponent}

Some users manually enters different types of links. In that scenario we can redirect to one page. For example User is trying to open Login page but he enters http://facebook.com/log. If the user enters like this also we can redirect to login page.

{ path:'login', component:Logincomponent }, 

{ path: 'log' ,redirectTo:'login' patchmatch:'full' }

Thease are the basic things to know about routing. Practice more to gain good knowledge.

Thanks

Discover and read more posts from Sadhana Reddy
get started
post commentsBe the first to share your opinion
Show more replies