Routing Strategies
Written By: Avinash Malhotra
Updated on
Angular Routing use HTML5 PathLocationStrategy by default. In PathLocationStrategy, the url will be like https://domain.com/pathname. It is the default Strategy used path Angular for routing.
Although there is another type of Strategy for routing in angular, and that is HashLocationStrategy. Its us hash (#) in url then pathname.
Types of Routings Strategies
- path location based ( default )
- hash url based
Gmail since beginning use hash location Strategy. Like #inbox, #sent, #all in URL. https://mail.google.com/mail/u/0/#inbox is the default homepage URL once gmail is loaded.
PathLocationStrategy
PathLocationStrategy is the default Routing Strategy in Angular. It use HTML5 pushState API in JavaScript History Object for routing.
base href="/"
Angular Application already includes <base href="/"> in index.html page for PathLocationStrategy based routing. By using this, the URL can change without requesting server. Also the hash fragment is not required.
index.html
<!--index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyApp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
path url examples
HashLocationStrategy
Angular HashLocationStrategy are another way to use Routing. Hash based Routing is very old. In fact its still in use in some old and new web applications.
HashLocationStrategy can be used on legacy browsers like internet explorer.
app.config.ts
In component file. import RouterLink and RouterLinkActive. RouterLink means this hyperlink is link of router and RouterLinkActive means this router is currently active.
<!--app.config.ts-->
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withHashLocation } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes, withHashLocation())]
};