What causes Bootstrap 4 elements to initiate a full reload of an Angular 7 application?

Currently, I am utilizing bootstrap 4 and angular 7 in my project. The element below is responsible for toggling the visibility of a sidebar:

<a
  class="app-sidebar__toggle"
  href="#"
  data-toggle="sidebar"
  aria-label="Hide Sidebar"
></a>

The issue arises when I access a specific route, causing a full page reload. Here are the routes defined in app-routing.module.ts:

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'catalogo/lista', component: CatalogoListaComponent },
  { path: '', redirectTo: 'home', pathMatch: 'full' }
];

If I navigate to http://localhost:4200/home, the error occurs. However, if I visit any other route (with the default empty route redirecting to /home), e.g., http://localhost:4200 or http://localhost:4200/a_route_that_not_exists, I get redirected to /home as expected, and the sidebar show/hide button functions correctly.

I hope this explanation clarifies my predicament, and your assistance would be greatly appreciated.

EDIT: Further code snippets from my application...

This snippet shows my app.component.html:

<app-header></app-header>

<app-sidebar></app-sidebar>

<div class="app-content">
  <app-title [titulo]="titulo" [icono]="icono [breadcrumbs]="breadcrumbs"></app-title>
  <router-outlet></router-outlet>
</div>

Below is my header.component.html (includes the link for toggling the sidebar):

<header class="app-header">
  <a class="app-header__logo" href="index.html">Vali</a>
  <!-- Sidebar toggle button-->
  <a
    class="app-sidebar__toggle"
    href="#"
    data-toggle="sidebar"
    aria-label="Hide Sidebar"
  ></a>
  <p>.... more html</p>
</header>

Lastly, here's the content of my sidebar.component.html:

<div class="app-sidebar__overlay" data-toggle="sidebar"></div>
<aside class="app-sidebar">
  <div class="app-sidebar__user">
    <img
      class="app-sidebar__user-avatar"
      src="https://s3.amazonaws.com/uifaces/faces/twitter/jsa/48.jpg"
      alt="User Image"
    />
    <div>
      <p class="app-sidebar__user-name">John Doe</p>
      <p class="app-sidebar__user-designation">Frontend Developer</p>
    </div>
  </div>
  <ul class="app-menu">
    <li>
      <a class="app-menu__item" [routerLink]="['/home']">
        <i class="app-menu__icon fa fa-home"></i>
        <span class="app-menu__label">Inicio</span>
      </a>
    </li>
    more menu elements...
  <ul>
</aside>

Answer №1

When it comes to integrating Popper/ JS elements from Bootstrap into Angular, there are some challenges; however, Angular offers a reliable way to manage elements like sidenavs.

If the element responsible for toggling the sidenav is not in the same component as the sidenav itself, you can create a basic service to handle the state of the sidenav. To set up your sidenav service (execute this command in your project root using the console):

ng g s sidenav

In the generated sidenav.service.ts file, include the following:

import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';

@Injectable()
export class SidenavService {
  public isOpen: boolean = false;
  public toggleChange: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

  constructor() {}

  public toggle(): void {
    this.isOpen = !this.isOpen;
    this.toggleChange.next(this.isOpen);
  }
}

In your header.component.html, adjust the clickable element that will show/hide the sidebar:

<a
  class="app-sidebar__toggle"
  aria-label="Hide Sidebar"
  (click)="toggleSidebar()"
></a>

In your header.component.ts file, define the toggleSidebar() method to call the toggle() function from the service you just created:

import {SidenavService} from "[location of your service]";


@Component({ /*...*/ })
export class HeaderComponent {

  constructor(private sidenavService: SidenavService)

  toggleSidebar(): void {
    this.sidenavService.toggle();
  }

}

You can then implement the reaction to the toggle (either in your app component or sidebar component):

//assuming you're in sidebar.component.ts
import {SidenavService} from "[location of your service]";
import {OnInit, OnDestroy} from "@angular/core";
import {Subscription} from "rxjs";

@Component({ /*...*/ })
export class SidebarComponent implement OnInit, OnDestroy {
  isOpen: boolean;
  sidenavSubscription: Subscription;

  constructor(private sidenavService: SidenavService) {}

  ngOnInit() {
    this.sidenavSubscription = this.sidenavService.toggleChange.subscribe(isOpenChange => {
      this.isOpen = isOpenChange;
    });
  }

  ngOnDestroy() {
    this.sidenavSubscription.unsubscribe();
  }
}

You can utilize the isOpen variable in your sidebar component in various ways to control the sidebar's behavior. For instance, you can use an [ngClass] directive:

<!--in your header component-->
<header [ngClass]={'active': isOpen, 'inactive': !isOpen} >
</header>

Alternatively, you can incorporate angular animations to animate the sidebar in and out (using ngIf and the :enter/ :leave transitions).

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

Using Angular 2 to submit ngModel data within an ngFor loop

When submitting the form, an error occurs when trying to repopulate the data back to the form: ERROR TypeError: Cannot read property 'id' of undefined This is in reference to the code snippet: <select [(ngModel)]="insurer.group.id" name="grou ...

Using Angular 4 to transfer data from a dynamic modal to a component

Currently implementing material design, I have set up a dialogService for dynamically loading MdDialog. My goal is to create a search dialog with filters that, upon submission, directs the user to a search-results component route. However, I am struggling ...

Angular 11 with angular-material no longer displays a button ripple effect in the color primary, accent, or warn

I have a set of 4 basic buttons using Angular Material, including imported BrowserAnimationsModule: <button mat-button mat-raised-button > TEST </button> <button mat-button mat-raised-button color="primary"> TEST primary</bu ...

Hover without proper anchoring / move to section on click without anchor tag

I need assistance with a jump tab feature I am implementing on my portfolio website. I have encountered a couple of issues that I could use some help with. https://i.sstatic.net/8hwgL.png <ul class="section"> <li><span>home& ...

Visual feedback on Bootstrap button outlines when clicked

https://i.sstatic.net/A78vB.png Hello, I'm currently working on styling the border around the primary button (btn-primary) and I'm facing an issue where a light blue border appears after clicking which seems to be unaffected by adjusting the out ...

Having issues with my *ngFor loop in Angular 11. Any assistance in resolving this problem would be greatly appreciated

Utilizing *ngFor, I am sending an array from typescript to the HTML page. kitUser: any=[]; constructor(private service: AdminService) { } ngOnInit() { this.service.getKSignUps().subscribe(res=>{ this.kitUser=res; console.log(this. ...

Creating a Full Screen Image with HTML and CSS

On my current web project, I am aiming for an immediate impact with a full-screen image that transitions to reveal text and information when the user starts scrolling. The challenge lies in ensuring this effect is consistent across various screen resolutio ...

What is the best way to set up the --public-host for operating an Angular universal app in conjunction with an Ngin

Looking to implement HMR for a universal app, I want to confirm if it is possible. I have successfully set up and run an Angular 8 application using the default "ng new" command. To run it behind a reverse proxy, I modified npm start as follows: e.g. { " ...

CSS background color using over 20 different shades

I am seeking a way to dynamically change the background color of an object based on a specific value. Specifically, I want to create a percentage bar with 100 different background colors possible, corresponding to each percent (excluding when empty). The w ...

Angular failing to recognize the && operator

I have a button that opens a dialog with the blockui feature. I am trying to close the dialog and set the blockui boolean variable to false in order to stop blocking the UI. However, in my HTML code (click)="blockedDialog=false && displayAddDialog=false", ...

Ways to create distance between repeated cards in a loop. My method involves utilizing ajax, jquery, and bootstrap

view image description here What is the best way to create some space between these closely aligned cards? .done((todos) => { todos.forEach(el => { console.log(el) $("#todo-list").append(` <d ...

Arrange my Firebase Angular users based on a specific value, encountering an error stating "sort is not a function

I'm working on an application using Firebase and Angular, and I have a database containing information about my users: https://i.sstatic.net/KQNSY.png My goal is to sort the users based on their "ptsTotal". In my users.service file, I have a functi ...

Is Node.js and Express.js necessary when utilizing Angular2 in development?

A web application prototype was developed using the following technologies: Angular 2 TypeScript ASP.Net WebAPI 2 Mongo DB Karma/Jasmine Node.js (solely as a server, in accordance with Angular2 Quick Start instructions) Given the tech stack mentioned ab ...

Align the elements of the contact form to the opposite sides

I am experiencing an issue with my contact form where all elements are flowing horizontally instead of vertically. I would like everything to be floated to the left and aligned vertically, except for the "message" box and submit button which should be on t ...

Issue with consistent search autocomplete feature in a stationary navigation bar using bootstrap technology

My issue is with the autocomplete box - I want it to have the same width as the entire search box. Something like this using Bootstrap's col-xs-11 class: https://i.sstatic.net/npzhC.png If I set the position to "relative," it looks like this (all st ...

Is there a way to implement a JavaScript function that can dynamically update the color scheme and background colors of all HTML pages within my website?

Looking for help on implementing a Javascript function that can modify the color schemes and background on all pages of my website. I tried using a function but it's only affecting one page. Can anyone offer guidance or suggestions? I'm finding t ...

In Chrome, a horizontally floating item is pushed down, whereas in Firefox it remains in place

What is causing the last item in the submenu to be lower than the rest in Chrome, but aligned in Firefox? Check out this JSFIDDLE with font turned red for visibility View the ACTUAL SITE here I've experimented with padding, margin, vertical align, ...

Utilize Datatables to apply filters dynamically

For displaying a list loaded via an AJAX call to the server, I utilized the datatables jQuery plugin. To integrate the search input inside my sidebar, I made use of the bFilter property to hide the filter. $(function () { var generatedCustomerTable = ...

What is the process of linking a contact form to send an email using Golang?

I've been attempting to connect my golang server to my HTML contact form, and here is the organization of my folders You can view the folder structure in the image below.. Here is the content of the server.go file: package main import ( "htm ...

"Add some pizzazz to your website with Animate.css - Animate your

I am looking to create a dynamic effect where three words slide in and out individually. The first word should slide in and out, then the second word, and so on. How can I make this happen? Here's what I've tried: HTML: <p class="fp-animate ...