I am hoping for the bootstrap collapse feature to automatically close one section when another is expanded

I tested this code and it worked for me, but when I try to use it in Angular, I encounter an error in jQuery stating that "collapse tag is not found in jQuery". Can anyone assist me in resolving this issue?

$('.button-click').click( function(e) {
    $('.collapse').collapse('hide');
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>



  <a class="btn btn-primary button-click" data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
    Link with href
  </a>
 
   <a class="btn btn-primary button-click" data-toggle="collapse" href="#collapseExample2" role="button" aria-expanded="false" aria-controls="collapseExample">
    Link with href
  </a>

<div class="collapse" id="collapseExample">
  <div class="card card-body">
    Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
  </div>
</div>

<div class="collapse" id="collapseExample2">
  <div class="card card-body">
    Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
  </div>
</div>

Answer №1

Using Angular along with Bootstrap is recommended over using jQuery with Angular, as it helps avoid potential issues. Consider utilizing Angular powered Bootstrap frameworks like ng-bootstrap.

Note: With the upcoming Bootstrap 5, jQuery support will no longer be included.

When integrating Angular powered Bootstrap using ng-bootstrap, you have two choices:

  1. Implement ng-bootstrap's collapse feature, demonstrated in this stackblitz example:
<button type="button" class="btn btn-primary" [class.active]="!isCollapsed" (click)="isCollapsed2 = true; isCollapsed = !isCollapsed"
          [attr.aria-expanded]="!isCollapsed" aria-controls="collapseExample">
  Link with href
</button>
 
<div id="collapseExample" [ngbCollapse]="isCollapsed">
  <div class="card card-body">
    1 Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
  </div>
</div>

<div id="collapseExample2" [ngbCollapse]="isCollapsed2">
  <div class="card card-body">
    2 Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
  </div>
</div>

Alternatively, you can create custom Angular methods to replace jQuery's $('.collapse').collapse('hide'); functionality, as shown in this stackblitz example.

public isCollapsed = [false, true];
resetAllCollapsedAndToggleCurrent (index) {
  this.isCollapsed.forEach((item, collapseIndex) => {
    if (index === collapseIndex) {
      this.isCollapsed[index] = !this.isCollapsed[index];
    } else {
      this.isCollapsed[collapseIndex] = true;
    }
  })
}

... with corresponding HTML:

<button type="button" class="btn btn-primary" [class.active]="!isCollapsed[0]" (click)="resetAllCollapsedAndToggleCurrent(0)"
          [attr.aria-expanded]="!isCollapsed[0]" aria-controls="collapseExample">
  Link with href
</button>

<div id="collapseExample" [ngbCollapse]="isCollapsed[0]">
  <div class="card card-body">
    1 Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
  </div>
</div>
  1. A similar behavior to collapsing elements is achieved with tabset pills, which you can easily adapt for your project using this stackblitz example:
<ngb-tabset type="pills">
  <ngb-tab title="Link with href">
    <ng-template ngbTabContent>
      <p>1 Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.</p>
    </ng-template>
  </ngb-tab>
  <ngb-tab title="Link with href">
    <ng-template ngbTabContent>
      <p>2 Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.</p>
    </ng-template>
  </ngb-tab>
</ngb-tabset>

Best of luck with your Angular projects!

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

Angular 9: Implementing a synchronous *ngFor loop within the HTML page

After receiving a list of subjects from the server, exercises are taken on each subject using the subject.id (from the server) and stored all together in the subEx variable. Classes are listed at the bottom. subjects:Subject[] temp:Exercise[] = [] s ...

What role do colors and tables play in Javascript?

Preparing for my upcoming Web Development exam, I stumbled upon an intriguing question:https://i.sstatic.net/m9T0F.png Here's how I tackled it: function pallete() { var components = ["00", "33", "66", "99", "CC", "FF"]; var conte ...

My jquery filter is not functioning properly

I need help making the active class work on each category when clicked, shifting to the next one. I've tried implementing it but no luck so far. $(document).ready(function() { $('.list-inline-item').click(function() { const value = ...

Converting jQuery ajax success response data into a PHP variable: A step-by-step guide

When sending data to a php page for processing using jQuery and ajax, I receive a response in the form of: success: function(data){ mydata = data; } The data retrieved is a URL represented as mydata = https://myurl.com. Now, I want to assign this data to ...

The alignment of vertical text can impact the positioning of surrounding text

I am working on creating an online portfolio using HTML and CSS, but I am facing a challenge with vertical alignment. My goal is to have a line of vertical text running down the left side of the screen that displays "My occupation". On the right side of t ...

What is the best way to choose all <pre> tags that have just one line of content?

$('pre:contains("\n")') will target all <pre> elements that have one or more newlines. Is there a way to specifically select <pre> tags with no newline or only one at the end? Any shortcuts available? match <pre>A< ...

Tips for clearing out text in a <p> tag with javascript when it exceeds a specific length of 100 characters

Is there a way to automatically truncate text to (...) when it exceeds 100 characters inside a paragraph with the class .class? For instance, if I have a long paragraph like this: <div class='classname'> <p>Lorem ipsum dolor sit ame ...

The Angular service/value is failing to retrieve the updated variable from the $(document).ready() function

Currently, I'm facing an issue with my Angular service/value. It seems to be grabbing the original variable instead of the new one that is supposed to be inside $(document).ready(). Here's the relevant code snippet: var app = angular.module("app ...

Tips on generating model names dynamically within a service

I am currently utilizing a service to assign unique numbers to model names. The resulting data structure is as follows: "sectionInputs": [ { "model": "price_min1" }, { "model": "price_max2" }, { "model": "units_occ3" }, { "m ...

increase the selected date in an Angular datepicker by 10 days

I have a datepicker value in the following format: `Fri Mar 01 2021 00:00:00 GMT+0530 (India Standard Time)` My goal is to add 60 days to this date. After performing the addition, the updated value appears as: `Fri Apr 29 2021 00:00:00 GMT+0530 (India St ...

Guide to centering the navigation bar within a container using Bootstrap 4

I'm looking to center the navbar on my webpage. How can I style it so that it appears in the middle of the page? Currently, it's aligned with the left side of the page. section class="navbarSection"> <div class="contain ...

The floating property doesn't appear to function properly in Internet Explorer versions 6 through 8 when

I've noticed that my website in Dutch looks great on Firefox and Safari (both Mac and PC), as well as Chrome (Mac tested, PC untested), but for some reason it's not displaying correctly on IE 6-8 (which is unavailable on Mac). I suspect there may ...

Leveraging the array for fetching JSON data

I'm currently utilizing this code snippet to parse json data: $.getJSON(geocodingAPI, function (json) { // Extracting variables from the results array var address = json.results[0].formatted_address; console.log('Address : ', a ...

Tips for Resolving This Issue: Dealing with Cross-Origin Read Blocking (CORB) Preventing Cross-Origin Response

Caution: jquery-1.9.1.js:8526 The Cross-Origin Read Blocking (CORB) feature has blocked a cross-origin response from with MIME type application/json. For more details, refer to . My Code snippet is as follows: <!DOCTYPE html> <html> <hea ...

I am seeking a way to access the child infoWindow within a Google Maps marker in Angular 5

I am working on an Angular 5 application that utilizes the Angular Google Maps(AGM) library available at . I have implemented functionality where clicking on an item in a list within one component triggers the display of a child infoWindow associated with ...

Utilize Angular to Transfer HTTP Array Data from a Service to a Component

As I work on developing an app with Angular, my current challenge involves a service that retrieves an Array of Data from an online source. My goal is to make this array accessible in other components but I'm facing difficulty in passing the data to t ...

What is the standard error function used for jQuery promises?

Is there a way to establish a default error handling function for a jQuery promise? I am running a series of functions asynchronously, and if any of them encounter an error, I want the error to be reported. Currently, this is how I have to handle it: fun ...

Unseen related model fields

I am struggling to figure out what is causing an issue in my code. Can anyone explain why the fields in locations = Location.objects.filter(user=add_profile.user) are not showing up on my html page? models.py class Location(models.Model): user = mode ...

Unable to get 100% height to work properly in HTML5 ASP.net because of the DOCTYPE

I'm currently working on creating an Asp.net website with a unique single-page portfolio style for the homepage. Each project or section should be 100% height of the viewport, stacked underneath each other to make use of anchor tags. However, I'm ...

Strategies for delaying the loading of CSS when importing

import 'react-dates/lib/css/_datepicker.css' The CSS mentioned can be deferred since it is not critical. Is it possible to defer the loading of CSS when utilizing import? I found information on deferring CSS loading using <link> from Goo ...