Using Typescript to collapse the Bootstrap navbar through programming

I've managed to make Bootstrap's navbar collapse successfully using the data-toggle and data-target attributes on each li element.

If you're interested, here is a SO answer that explains a way to achieve this without modifying every single li:

Below is a snippet of my navbar code featuring two of the li elements:

<div class="collapse navbar-collapse" id="navbarSupportedContent">
  <ul class="navbar-nav mr-auto">
    <li class="nav-item" data-toggle="collapse" data-target=".navbar-collapse.show">
      <a class="nav-link" href="#" routerLink="/servers">Servers</a>
    </li>
    <li class="nav-item" data-toggle="collapse" data-target=".navbar-collapse.show">
      <a class="nav-link" href="#" routerLink="/servers">Variables</a>
    </li>

I'm getting close to implementing this functionality in my Angular 8 Typescript file:

export class AppComponent implements OnInit {
  ngOnInit(): void {
    const navbarItems = document.querySelectorAll('.navbar-nav>li');
    navbarItems.forEach(navbarItem => {
      navbarItem.addEventListener('click', () => {
        const navbar = document.querySelector('.navbar-collapse').collapse('hide');
      })
    });
  }
}

The problem lies in the last line:

Property collapse does not exist on type element.

What steps should I take to fix this issue? Additionally, are there any alternative methods that could work better?

I have attempted to cast navbar as various HTML element types, but none of them seem to resolve the problem.

Answer №1

You have the option to approach it in a more Angular-oriented manner. Take a look at this example:

<button class="navbar-toggler" type="button" (click)="showMenu=!showMenu">
    <span class="navbar-toggler-icon"></span>
 </button>
 <div class="collapse navbar-collapse" [ngClass]="{'show':showMenu}">
     ...
 </div>

Answer №2

After some experimentation, I managed to achieve functionality by excluding 'show' from the list of classes, as illustrated in the final line.

(Although I'm uncertain about the effectiveness of this method, it is producing the desired results.)

public class AppComponent implements OnInit {
  ngOnInit(): void {
    const navbarItems = document.querySelectorAll('.navbar-nav li');
    navbarItems.forEach(navbarItem => {
      navbarItem.addEventListener('click', () => {
        const navbar = document.querySelector('.navbar-collapse');
        navbar.classList.remove('show');
      })
    });
  }
}

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

store JSON data within an HTML list element

I've been working on a JavaScript script that allows me to generate list items in HTML. Right now, I have functionality to drag and remove the items using another script. However, I am interested in adding some additional information to each list item ...

When dynamically accessed, the property of a JSON object is considered "undefined"

I'm running into trouble trying to access properties of a JSON object in my JavaScript code using obj[varWithPropName]. Strangely, it does work when I use obj["PropName"]. Here's a simplified snippet for reference: import * as CharInfo from &ap ...

Retrieve the values of two inputs from outside of the event

How can I access the values of two input fields in order to perform calculations as soon as their values are updated? <script> // Accessing the values of the two input fields for immediate calculation based on user input const heightInputEl = docum ...

View a specific selected newsAPI article on its own dedicated page

I have been working on a news website and successfully displayed all the articles on a single page using the news API in nodeJs. Everything is functioning well, but now I want to show the clicked article on a separate page. Although I managed to route it t ...

Retrieving data from an array using an AJAX request function

I've been attempting to utilize an AJAX call to update a series of image elements on a webpage. The array containing the elements to update is populated with URLs fetched from a PHP page via AJAX. The issue I'm encountering with the code provide ...

Utilizing Loopback Callbacks within a Looping Structure

While working in a for-loop, I encountered an issue where I needed to access the loop variable 'i' from within a callback function but it was not accessible due to closure restrictions. Despite attempting different methods such as using (i) or ca ...

Using scrollIntoView() in combination with Angular Material's Mat-Menu-Item does not produce the desired result

I am facing an issue with angular material and scrollIntoView({ behavior: 'smooth', block: 'start' }). My goal is to click on a mat-menu-item, which is inside an item in a mat-table, and scroll to a specific HTML tag This is my target ...

Error: The function Task.find is not recognized in Node.js

I've been encountering an issue with my model while connected to MongoDB and having a running server. The problem seems to be related to routing through the TaskController, but I'm not sure if it's due to the model or the find() function. I ...

The type unknown[] cannot be assigned to type React.ReactNode

import * as React from 'react'; import { List, ListItemButton, ListItemIcon, ListItemText, ListItem} from '@mui/material'; import LightbulbOutlinedIcon from '@mui/icons-material/LightbulbOutlined'; import NotificationsNoneOutl ...

"Debugging a simple demonstration showcasing NodeJS, AngularJS, and Express

Currently, I am following an online tutorial to learn a new concept. I have reached the part where I need to display data using HTTP GET from the controller, while the sample data is stored in the server file. I managed to fetch the data from the controlle ...

What is the most effective method for delivering npm packages using django?

Currently, I am utilizing django as the backend along with a few javascript packages installed via npm. To access these packages, I have configured django to serve /node_modules by including it in the STATICFILES_DIRS. While this setup has been functional, ...

modifying the child divs contained in the main div

Hey there! I'm currently using Bootstrap to design an application and I've got the entire form inside a container. However, as I add more child elements within the container div, I would like the parent div to expand automatically to show all the ...

The error message "TypeError: self.parent.parent.context.parseInt is not a function" indicates that

My goal is to set the height of an image using ngStyle by calculating it with a Math operation in the following way: <div [ngSwitch]="tbNm?tbNm:'itm0'"> <ion-list *ngFor="let vl of scrnshot;let ind=index"> <img *ngSwitch ...

Calculating the total of all values in a table

For my ngFor loop, the invoice total is calculated based on price and hours, but I also want to calculate the totals of all invoices in the end. <tr *ngFor="let invoice of invoiceItem.rows"> <td>{{ invoice.rowName }}</td> <td& ...

Tips for Effectively Declaring a Variable with React's useState

How should I correctly specify variable types in useState? In the code below, the value for alert must be either "success","warning", "error", or "info" const [alertValue, setAlertValue] = useState("error" ...

Is there a mistake in how I am creating this TypeScript object?

After selecting an item from a dropdown menu, I want to remove the select element and display the selected item in an ag-grid. Although the row is added to the grid successfully, the name/id properties do not appear correctly and the select element remains ...

Activate a jQuery plugin on elements that are dynamically generated

Here is the code snippet I am using: $(".address-geocomplete").geocomplete({ country: "US", details: ".details", detailsAttribute: "data-geo" }); When these elements are loaded with the document, everything works smoothly. However, there seem ...

Determine the image's position in relation to its parent element while factoring in any vertical offset

Within my HTML, I have arranged two images to sit adjacent to one another. Interestingly, one image happens to be taller than the other. Despite assigning a CSS property of vertical-align: middle to both images, the result is that the shorter image appears ...

Utilizing the Redux Connect HOC's wrapped component type in React.RefObject without the need for re-importing

My current setup involves a simple component that is wrapped with react-redux and has a ref with forwardRef: true, demonstrated below: // Button.tsx class Button extends React.Component { // ... } // ... export default connect(mapStateToProps, null, n ...

Obtain the dynamic identifier of an element within every block using jQuery in a rails application

Let me illustrate my issue with a simple example. I am currently developing a recipe application. Within the show partial that loads via AJAX, I have the following setup: _show.html.erb <% @recipe.ingredients.each do |ingredient| %> <div class ...