Angular mistakenly redirects to the local host at port 4200 with a hash symbol

After using

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

This is how I am redirecting from the showcard component to the newcard component:

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

The newcard component was generated by running ng generate component newcard.

Here is the content of my app-routing.module.ts file:

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 { }

Additionally, here is my app.module.ts file:

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 { }

Answer №1

Upon examination, a major issue that stands out is the <a> tag intended to go to localhost:4200/newcard.

The use of both href="#" and

(click)="onCreateNew()"
appears to be causing confusion as they lead to different routes. This can result in an error, where href is triggered first leading to localhost:4200/#/newcard or failure to open altogether.

Solution

To address this, it is recommended to remove the unnecessary href property from the <a> tag:

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

Additionally, consider using [routerLink] directly in your template for smoother navigation. Learn more at https://angular.io/api/router/RouterLink

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

If you have any further questions, feel free to ask!

Answer №2

Eliminate the href="#" from the <a> tag to prevent unintended redirection when clicked.

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

Alternatively, you can utilize the [routerLink] attribute instead of adding a click event.

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

View Demo on StackBlitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The versatile payment solutions offered by PayPal, including Adaptive Payments and Chained Payments, can be seamlessly

At this time, PayPal Adaptive Payments has been flagged as deprecated and there is no available frontend documentation. I have not been able to find a way to achieve this using the existing documentation. I am currently developing an Angular app that inte ...

Guide on creating a Jasmine test for a printer utility

Currently, I am working on writing a Jasmine test for the print function shown below: printContent( contentName: string ) { this._console.Information( `${this.codeName}.printContent: ${contentName}`) let printContents = document.getElementById( c ...

Switching between PascalCase and camelCase in TypeScript leads to unexpected behavior

Currently, I am in the process of transitioning a C# desktop application to an Angular/TypeScript web application. In the C# application, all class properties are named using PascalCase. Therefore, I decided to maintain this naming convention in the TypeS ...

What is the best way to specify Next.js Context types in TypeScript?

Can someone help me with defining the types for next js Context and req? Below is the code for the getServerSideProps function- //Server side functions export const getServerSideProps: GetServerSideProps = async (context) => { await getMovies(conte ...

submitting an angular form and resetting the values afterward

I've implemented the following Angular form and I want to clear the text field after submitting the form. <form #addcheckinform="ngForm" novalidate (ngSubmit)="addcheckinform.form.valid && saveScheduleCheckin(this.che ...

How can a TypeScript Angular directive utilize a function?

Recently, I have been following a unique Angular directive TypeScript pattern that I find really effective. The approach involves giving the directive its own isolated scope by creating a new controller. I encountered a scenario where I needed to invoke a ...

Mongoose failing to persist subdocument

After trying to insert into my collection, I noticed that the sub-document is not being saved along with it. This issue has left me puzzled. This is the scheme/model I am working with: import { Schema, Document, Model, model } from 'mongoose' ...

Potentially null object in react typescript

In my React application with TypeScript, I have completed the implementation of a chart but encountered an error in the following line: backgroundColor: gradientFill ? gradientFill : chartRef.current.data.datasets[0].backgroundColor, T ...

Using wildcard in Angular app for MQTT observation

My curiosity lies in MQTT wildcards and how they function, specifically while utilizing the mosqitto broker. Let's say I have around 1-2k topics. In my frontend, I am observing them with a single-level wildcard using ngx-mqtt. Will there be a separat ...

Exploring the contrasts and practical applications of Virtual Scroll versus Infinite Scroll within the framework of Ionic 3

After thoroughly reviewing the documentation for Ionic 3, I embarked on a quest to discern the disparity between https://ionicframework.com/docs/api/components/virtual-scroll/VirtualScroll/ and https://ionicframework.com/docs/api/components/infinite-scr ...

The stacked bar chart in Apex is not displaying correctly on the x-axis

Currently, I am utilizing the Apex stacked bar chart within my Angular 16 project. In this scenario, there are 4 categories on the x-axis, but unfortunately, the bars are not aligning correctly with the x-axis labels. The data retrieved from my API is as ...

Angular 2: How to Avoid Exceeding Maximum Call Stack Size with Eager Loading

I'm facing an issue with preloading all of my child route modules. In my root routing module, I have the following configuration: RouterModule.forRoot(appRoutes, { preloadingStrategy: AppCustomPreloader }) The structure of AppCustomPreloader is as f ...

Receiving a SyntaxError in Node.js with the message "Unexpected token *" while attempting to import

node: v10.16.3 npm: 6.12.0 Encountered an error while trying to import express in node. Referencing the code from https://github.com/angular-university/rxjs-course, specifically server/server.ts. To run server.ts, used the following command: $ ts-node ...

Finding the appropriate method to access a template variable reference in a designated row of an Angular Material table (Angular 7)

Currently, I am working on implementing a more intricate version of a behavior inspired by Angular Material's tutorials. In my simplified example, an Angular Material table is populated with data from a string array. The first column contains input fi ...

Using a Javascript library within an Angular component: A comprehensive guide

I've been working on a Web-Client project that involves visualizing sensor data such as velocity and acceleration within a coordinate system. In order to display this coordinate system, I decided to use the graph.js library from https://github.com/dhu ...

Using Fixed Patterns and Combining Types in an Interface

Presently, I am working with this interface: export interface User{ name: string birthday: number | Timestamp ... } When strictTemplates:false is enabled, I have no issue using this interface for server data retrieval with the birthday parameter in ...

Switching from a Promise to an Observable using React-Redux and TypeScript

I am struggling to grasp the concept of storing a Promise response into Redux. I believe finding a solution to this issue would greatly benefit me. Currently, I am utilizing a library that returns a Promise, and I wish to save this response - whether it i ...

Ngb-xx is not a recognized chemical property

Attempting to implement ngb bootstrap in my Angular project has been challenging. Errors keep popping up for every ngb component I try to use. https://i.sstatic.net/jF1xV.png Here's a glimpse of my package.json: https://i.sstatic.net/utqX6.png and ...

methods for array filtering in typescript

How do I filter an array in TypeScript? I attempted the following findAllPersonsNotVisited():Observable<Person[]> { var rightNow = new Date(); var res = rightNow.toISOString().slice(0,10).replace(/-/g,"-"); return this.db.list(& ...

Determine the size of a BSON object before saving it to a MongoDB database using

I am currently in the process of determining the best way to calculate the size before storing certain data in MongoDB. After writing a script that parses and combines data into a single document, I have encountered an error when trying to use instance.sav ...