Is there a way to swap out the current URL in TypeScript without causing a page refresh?

Is there a way to update the URL of a page in Angular 11 without causing a refresh?

I have tabs on my page, and when a tab is clicked, I want to add the name of the tab with a '#' prefix to the current URL. I've tried implementing this by checking the current URL, removing any existing '#', and adding the clicked tab's name. However, it doesn't always work correctly - only some tabs are functioning as expected. Is there an alternative method to update the URL without refreshing the page, ensuring that the navigation works correctly?

In my HTML:

<a href="#{{phase.TitleNew}}" title="" (click)="tabClick(phase.TitleNew)">{{phase.Title}}</a>
 <div class="c-arquetype-phase__block -one" id="{{data.Phases.TitleNew}}">

In my typescript file:

 tabClick(phase: any) {

this.flag = 1;
if (this.flag == 1 && this.router.url.includes('#')) {
  let hashIndex = this.router.url.indexOf('#');
  this.finalUrl = this.router.url.substr(0, hashIndex);
  this.finalUrl = this.router.url.substr(0, this.router.url.lastIndexOf("#"));
}
else {
  this.finalUrl = this.router.url;
}
this.hrefUrl = this.finalUrl + '#' + phase;
this.archetypePhases.forEach(data => {
  if (data.TitleNew === phase) {
    data.isClicked = true;
  }
  else {
    data.isClicked = false;
  }
})
this.location.replaceState(this.finalUrl + '#' + phase);

}

Answer №1

The built-in feature of hash anchors should automatically add #content to the URL and scroll to it without the need for any TS code. (As long as phase.TitleNew resolves to an ID present on a page element)

<a href="./#{{phase.TitleNew}}">Tab1</a>

If this doesn't work, you can set the hash property on the location object using an onclick event like so:

<a href="./#{{phase.TitleNew}}" onclick="event.preventDefault(); location.hash='{{phase.TitleNew}}';" >Tab1</a>

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

Oops! It seems like you forgot to indicate a command before proceeding. Make sure to check out the available commands using '--help'

I keep encountering the following problem: Error: A command must be specified before proceeding. Use '--help' to see the available commands. whenever I try to use an ng command. ...

What is the best way to showcase a half star rating in my custom angular star rating example?

component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { projectRating ...

The given 'FC<ComponentType>' type argument cannot be assigned to the 'ForwardRefRenderFunction<unknown, ComponentType>' parameter type

Currently, I am using react in conjunction with typescript. Within my project, there are two components - one serving as the child and the other as the parent. I am passing a ref to my child component, and within that same child component, I am binding my ...

How can the commit hash be injected into the environment.ts file using angular-cli?

Can the environment object be generated asynchronously? Background: I am looking to include the commit hash in my application. My idea is to utilize the environment.ts file for this purpose. However, obtaining the current commit hash requires an asynchron ...

Discover the process of changing a prop with a button click in NextJS

In my NextJs project, I have a video player component that displays videos using a {videoLink} prop: <ReactPlayer playing={true} controls={true} muted={true} loop={true} width="100" height="100" url={videoLinkDeep} poster="ima ...

Refine the search results by focusing on a specific property value

Assume I have a type defined as follows: type Result = {error:true,response: undefined} | {error:undefined, response:{nick:string}} This type will either contain an error property or a response, but not both. Now, I am attempting to create a function tha ...

Encountering an issue while trying to launch an Angular application on localhost. Vendor.js resource failed to load

Whenever I compile the code, it runs successfully. However, when I try to serve the application using 'node --max-old-space-size=8192', even though it compiles without any errors, when I open the app in a browser, it returns an error saying "Cann ...

Problems with importing modules in Apollo Server

I've encountered a never-ending stream of error messages post importing Apollo Server into my Typescript-based Node.js application. (Check out the screenshot below) It appears that Apollo is unable to locate anything in the graphql dependency. Could ...

Consuming Web API REST with Angular 2: Implementing Http delete method with custom Headers

After switching to Angular 2 Release, I started using Http and Headers from @angular/http. Everything seemed to be working fine as I called verbs like POST, GET, and PUT. However, I ran into an issue when trying to use the "DELETE" verb. Here is a snippet ...

Suitable typing for imported components lacking a common interface implementation

Looking for a way to avoid duplicating the array entries: import { ComponentA } from './components/A.component'; import { ComponentB } from './components/B.component'; const COMPONENTS: any[] = [ ComponentA, ComponentB ]; @NgModu ...

Angular and Bootstrap do not support margin styles

While working with Angular 5 and Bootstrap, I have encountered an issue with using inline styles for margin. The template I am using is as follows: @Component({ selector: "dynamic-container-component", template: ` <div styl ...

The issue arises when attempting to build because the FormBuilder is not recognized as a

I am facing an issue with my Angular app when trying to launch it locally. The error message "Error FormBuilder is not a NgModule" keeps appearing despite trying various solutions such as npm install and checking the package.json file. I have exhausted all ...

Choosing multiple items with an identical label but distinct objects can be accomplished with ng-select

I am facing an issue with selecting multiple items in the ng-select dropdown. Since I have not specified a bindValue, the items should be bound by objects according to the documentation found here. However, when attempting to do so, the items are being se ...

JSX is restricted in files using the '.tsx' extension according to eslint rules (react/jsx-filename-extension)

When working in a .tsx file, why does eslint flag the following issue: The use of JSX is not permitted in files with the extension '.tsx' (eslint react/jsx-filename-extension) What steps can I take to adjust the eslint configuration and addres ...

What steps are needed to develop a TypeScript component within Angular framework?

I've been attempting to develop an Angular Component in TypeScript. I'm trying to utilize document.createElement to build a toolbar within my component, but it's not appearing. Below is my Component code: import {Directive, Component, boot ...

Issue arising from swiper version 8 compatibility with angular version 16

After upgrading my Angular application to version 16 and implementing swiper version 8, I encountered errors when running the build:ssr command. The specific error message I received was: ./src/app/modules/pages/enterprise-price-list/enterprise-price-list. ...

Constantly scrolling screen in android Webview

When working with an Android web view, I encountered a bug related to infinite scrolling. Interestingly, removing the routerLink in certain pages resolved the issue, but not consistently across all cases. Is there a way to address this bug from the Android ...

Angular 6: A guide to dynamically highlighting navbar elements based on scroll position

I am currently building a single page using Angular 6. The page is quite basic, and my goal is to emphasize the navbar based on scrolling. Below is the code snippet I am working with: .sticky { position: sticky; top: 0; } #i ul { list-style-type: ...

Unlocking the Power of Azure Key Vault with Angular for Securing Your Secrets

Can Azure Key Vault be utilized to retrieve a vault access secret within an Angular application? I am currently building with Azure Active Directory using implicit flow, which means I am developing everything without a backend. Within my Angular project, ...

Eliminate information from Firestore with Angular

https://i.sstatic.net/MFKHB.png I encountered an issue while attempting to delete data from Firestore. Fetching and adding data is functioning correctly, but when attempting to delete data, it does not get removed and no error is displayed on the console. ...