Angular: Remove Hash (#) from URL like a charm

Leo N
2 min readJul 3, 2020
https://cdn.searchenginejournal.com/wp-content/uploads/2019/04/the-seo-guide-to-angular.png

Scenario

I am trying to remove the # sign from the url in Angular 2 but I couldn’t find any good explanation about how to remove it without generate any problem.

I remember on AngularJS 1 it was easier adding $locationProvider.html5Mode(true);

Also I would appreciate if you can tell me if this is a good practice (removing #) or could affect the SEO for the application (or improve it).

Defination — LocationStrategy

Applications should use the Router or Location services to interact with application route state. For instance, HashLocationStrategy produces URLs like http://example.com#/foo, and PathLocationStrategy produces http://example.com/foo as an equivalent URL. Enables the Location service to read route state from the browser's URL. Angular provides two strategies: HashLocationStrategy and PathLocationStrategy.

Step 1

Beside the module providers, check your module imports, it can also be overridden by providing the { useHash: true } as the second argument of the RouterModule.forRoot:

imports: [
...
RouterModule.forRoot(routes, { useHash: true }) // remove second argument
]

Step 2

Look into app.module.ts where app is bootstrapped there you have

@NgModule({
.......
providers: [
....
{ provide: LocationStrategy, useClass: HashLocationStrategy },
....
]
});

And remove this part since PathLocationStrategy is default strategy

Step 3

  • Import

import { LocationStrategy, Location, PathLocationStrategy } from ‘@angular/common’;

Add following to the ‘providers’ list

Location, {provide: LocationStrategy, useClass: PathLocationStrategy}

If the ‘HashLocationStrategy’ is already listed in the ‘providers’ list, that should be removed.

Now your application and all routings will be served

Note

When you change LocationStrategy your back-end will be affected because the back-end doesn't understand all of…

--

--

Leo N

🎓 “A person who never made a mistake never tried anything new.” — Albert Einstein