The RouterLink functionality may not work properly within a nav-bar that combines Bootstrap and Angular frameworks

I have a navigation bar that I want to modify for scrolling behavior based on the type of link.

For href links with the "#" symbol, I want the navigation bar to scroll down. However, for routerLink links, I want the page to navigate to the specified route:

<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark fixed-top" id="mainNav">
<div class="container">
    <a class="navbar-brand js-scroll-trigger" href="#page-top">hFinder</a>
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse"
            data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false"
            aria-label="Toggle navigation">
        Menu
        <i class="fas fa-bars"></i>
    </button>
    <div class="collapse navbar-collapse" id="navbarResponsive">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link js-scroll-trigger" href="#cards">Cards</a>
            </li>
            <li class="nav-item">
                <a class="nav-link js-scroll-trigger" href="#impressum">Impressum</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" [routerLink]="['/']">Start</a>
            </li>
        </ul>
    </div>
</div>

Although the link is positioned at the top, clicking it does not work. The card and impressum sections scroll down as expected.

https://i.sstatic.net/Kxdvk.png

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

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SedcardComponent } from './sedcard/sedcard.component';
import { StartComponent } from './start/start.component';

const routes: Routes = [
    { path: '', component: StartComponent },
    { path: 'sedcard/:id', component: SedcardComponent }
];

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

Additionally, here are the details from the console:

Router Event: NavigationStart NavigationStart(id: 1, url: '/') NavigationStart {id: 1, url: "/", navigationTrigger: "imperative", restoredState: null}

Router Event: RoutesRecognized RoutesRecognized(id: 1, url: '/', urlAfterRedirects: '/', state: Route(url:'', path:'') { Route(url:'', path:'') } ) RoutesRecognized {id: 1, url: "/", urlAfterRedirects: "/", state: RouterStateSnapshot}

Answer â„–1

If you're looking for a way to achieve fragmentation in Angular, there are a few things to keep in mind.

Firstly, avoid using href="#yourcontent" as it will redirect your page to a specific URL. Instead, consider the following approach:

<div class="collapse navbar-collapse" id="navbarResponsive">
    <ul class="navbar-nav ml-auto>
        <li class="nav-item">
            <a class="nav-link js-scroll-trigger" (click)="moveToCard()">Cards</a>
        </li>
    </ul>
</div>

Additionally, make use of Template reference variables in your HTML:

<div #Test>
   <div>
       <p>Your content</p>
   </div>
</div> 

In your TypeScript file, you can then call the following method:

@ViewChild('test') public test : ElementRef;

public moveToCard():void {
    this.test.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'start' });
}

Alternatively, you can use the following method:

In your TypeScript file:

changeFragment(value) {
    document.querySelector('#' + value).scrollIntoView({ behavior : 'smooth' });
};

In your HTML file:

<p id="divA">
  <strong>This is Div A</strong>.<br>
    <button (click)="changeFragment('divB')">Jump to Div B</button>
</p>

<p id="divB">
    <strong>This is Div B</strong>.<br>
    <button (click)="changeFragment('divA')">Back to Div A</button>
</p>

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

Encountering a 404 error in Angular 9 when refreshing the browser

Encountering a 404 error when attempting to access mysite.com/menu directly, but no issues when navigating through the homepage and selecting the menu option. Tried implementing an .htaccess file following Angular documentation, yet problem persists. Cur ...

What is the best way to update a BehaviorSubject holding an array without replacing the entire array?

When it comes to adding items to an array BehaviorSubject, the common practice is to assign a copy of the entire array along with the new item using next(). However, I am looking for a way to push items into this array without having to assign a full copy ...

Setting up Typescript: The Guide to Declaring a Dependent Property

In my current project, I am working on creating a declaration file for the quadstore library. This library has a class that requires a constructor parameter called contextKey. The value of this parameter determines the name of a field on method arguments. ...

Summing values in es6 (TypeScript) without explicitly knowing their corresponding keys

I am facing a challenge with an object that has changeable keys, which I do not want to rely on. The keys in this object are not fixed. Here is an example: interface Inf { [key: string]: number } const obj: Inf = { '2020-01-01': 4, '2 ...

Issue: Inadequate parameters have been supplied for the localized pathname (getPathname()). This problem arose after the inclusion of "next-intl/routing" module

After implementing the config file and replacing : Navigation File import { createLocalizedPathnamesNavigation, Pathnames } from 'next-intl/navigation'; With : Config File import {Pathnames, LocalePrefix} from 'next-intl/routing';} ...

What is the best way to specify the type of a property that has already been assigned

I am currently utilizing a third-party library that includes a type defined as the following: export interface ThirdPartyNodeType { id: string; name: string; data: any; } Upon further exploration, I have identified the content that I intend to include ...

Angular and Spring Boot integration with Apereo CAS application

For my current project, I am building an application with Angular6 for the frontend and spring boot for the backend. Initially, all APIs in my backend are open to everyone, accessible via URLs like localhost:8080/api/get_data from the frontend. However, I ...

Transforming a string into key-value pairs using Typescript

Is there a way to transform the given string into key-value pairs? TotalCount:100,PageSize:10,CurrentPage:1,TotalPages:10,HasNext:true,HasPrevious:false ...

Angular mistakenly uses the incorrect router-outlet

Encountering an issue with Angular routing. The main app has its own routing module, and there is a sub module with its own routing module and router-outlet. However, the routes defined in the submodule are being displayed using the root router outlet inst ...

Guide to triggering a method upon initialization of a select box in an Angular application

I have a situation where I am using a select box within a dynamically generated row. The row is created using a loop, and I need to execute a method when the select box is initialized. This method should receive the data associated with the row as an argum ...

The 'clientX' property is not recognized on the 'Event' type in Angular2 Directive

When attempting to retrieve the X position of my mouse in an Angular2 Directive using the following code: @HostListener('mousemove', ['$event']) onMousemove(event: Event): void { console.log(event.clientX) } I encountered an error ...

Passing Imported Module to Feature Module in Angular 7

In my Angular 7 app, I have set up a hierarchy of feature modules. The structure looks like this: app admin (UI module imported here) feature1 feature2 public Within the admin module, I have included a UI framework module. My question is, if modules ...

Encountering difficulty utilizing Partial with a generic type

I'm currently working on developing a class called Map that will store mappings set by other classes, such as CharacterManager. I want the content of the map to be determined by other classes, so I have designed the Map class to accept a generic typ ...

Separate configurations for Webpack (Client and Server) to run an Express app without serving HTML files

I am currently developing an application with a Node Backend and I am trying to bundle it with Webpack. Initially, I had a single Webpack configuration with target: node. However, I encountered issues compiling Websockets into the frontend bundle unless I ...

What are the steps to ensure a successful deeplink integration on iOS with Ionic?

Recently, I was working on a hybrid mobile app for Android/iOS using Nuxt 3, TypeScript, and Ionic. The main purpose of the app is to serve as an online store. One important feature involves redirecting users to the epay Halyk website during the payment pr ...

Encountered an issue while configuring the Apollo server - The type '() => void' cannot be assigned to type '() => DataSources<object>'

I need help with a TypeScript-related issue. I am struggling to implement the expected return type for the function dataSources in this scenario. Here is the code snippet: const dataSources = () => { quizzessApi: new QuizzessDataSource(); } const ...

Typescript: searching for a specific type within an array of objects

The title may be a bit unclear, but I'm struggling to find a better way to explain it. I have a predefined set of classes from a third-party library that I cannot modify. The specific content of these classes is not relevant, as it's just for i ...

Does Node initialization dependencies start with Express being initialized first?

Currently experiencing an issue with the initialization process of a system. To kick off the initialization, the index.ts file is being invoked. Within this file, there is an import of an initializer class named StartServer. This class contains an async me ...

Angular 6 - Use *ngIf to apply the readonly attribute to an input when a certain condition is met

In my current project, I am attempting to set a condition on an input field where if a variable equals 'view', then the readonly attribute should be added to the input. Here is the code snippet I am currently using: <input *ngIf="mode == &ap ...

The symbol displayed on the computer screen representing the software known as Angular 2

Can a desktop icon be created for an Angularjs 2 application? I am looking to have an icon that, when clicked, opens the application's URL in the browser. ...