Search code examples
angulartypescriptangular2-routing

Angular unintentionally redirects to localhost:4200/#


When attempting to this.router.navigate(['newcard']); it correctly loads the URL but then immediately redirects to localhost:4200/#.

Here is how I'm redirecting from showcard to newcard.

<a href="#" class="btn btn-primary" (click)="onCreateNew()">
  <i class="bi bi-plus"></i>
</a>
onCreateNew(){
  this.router.navigate(['newcard']);
}

newcard is the default generated by running ng generate component newcard

Here is my app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { NewcardComponent } from './newcard/newcard.component';
import { ShowcardsComponent } from './showcards/showcards.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';

const routes: Routes = [
  {path: 'newcard', component:NewcardComponent},
  {path: '', component:ShowcardsComponent},
  {path: '**', component: PageNotFoundComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { useHash: false })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

And here is my app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { HttpClientModule } from '@angular/common/http';

import { NewcardComponent } from './newcard/newcard.component';
import { ShowcardsComponent } from './showcards/showcards.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';

@NgModule({
  declarations: [
    AppComponent,
    NewcardComponent,
    ShowcardsComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgbModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Solution

  • As far as I can see, the first problem that comes to my mind is your <a> tag which is meant to navigate to localhost:4200/newcard.

    You are using href="#" and (click)="onCreateNew()" which are 2 different routes and probably create the error, since the href gets called first and after that the route doesn't match anymore because it would open localhost:4200/#/newcard or just fails otherwise.

    Solution

    Remove the unused href property in your <a> tag like this:

    <a class="btn btn-primary" (click)="onCreateNew()">
      <i class="bi bi-plus"></i>
    </a>
    

    I also recommend you to use [routerLink] directly in your template. https://angular.io/api/router/RouterLink

    <a class="btn btn-primary" [routerLink]="newcard">
      <i class="bi bi-plus"></i>
    </a>
    

    Hope this helps, reach out if you have more questions!