Toumi
Toumi

Reputation: 3155

Why angular routing adds hashtag # to the url

Version Used

Angular version : 7.10 @angular/router": "~7.2.0",

The question is

Why angular adds a hashTag to the url.

Example case:

const routes: Routes = [
  {
    path: 'aktion',
    component: AktionComponent
  }

does match the url

http://localhost:4200/aktion

but does not match the url

http://localhost:4200/#/aktion

Upvotes: 8

Views: 14778

Answers (4)

Patrick
Patrick

Reputation: 99

In Angular 17 the new syntax to enable hash based routing is the following:

export const appConfig: ApplicationConfig = {
   providers: [
     provideRouter(routes, withHashLocation()),
     //your other providers
   ]
};

The hash based routing feature ist used because some web providers dont deleagte the requests inside the angular application. They try to handle the request by its own. In yor example, for http://localhost:4200/aktion a webserver watchs for a file with name aktion. Since there is no such file, the server respons with 404. With the # the server interpret the request as a file request and delegate all requests inside the angular app.

Upvotes: 2

Dhananjai Pai
Dhananjai Pai

Reputation: 6015

If you are using the PathLocationStrategy then the server should be configured to send the error page also as index.html since normally this would result in a 404 and Angular should parse the route.

To avoid the hassle, the HashLocationStrategy may be used, since any part after # is ignored by the server and is only parsed from the browser. Hence you have the #. To remove it you can update the RouterModule configuration as shown by the other answers.

RouterModule.forRoot(AppRoutes, { useHash: false }),

Upvotes: 3

Manzurul Hoque Rumi
Manzurul Hoque Rumi

Reputation: 3094

In app module, do like this

@NgModule({
  imports: [
  // other imports
    RouterModule.forRoot(routes, { useHash: true }) //make it false
  ],
  declarations: [
  ],
  providers: [

  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

Upvotes: 9

Jignesh Mistry
Jignesh Mistry

Reputation: 2479

If you have add this line to App Module then it adds #

   RouterModule.forRoot(AppRoutes, { useHash: true }),

Upvotes: 3

Related Questions