Exploring the possibilities of updating carousel items in Angular using Bootstrap

I'm working on a project where I have 4 images and a carousel that needs to navigate to the respective index when one of the images is clicked. The challenge is that the carousel is built with Bootstrap and jQuery, but the rest of the application is Angular. To try and solve this, I am using elementRef to select the carousel component. However, I am struggling to change the slides as desired. When I console.log the ElementRef, I only see the HTML. Is there a more effective approach to achieve this?

component.html

            <!-- Carousel -->
            <div *ngIf="collection === 'Boudoir'" class="card img-row ">
                <div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
                  <div class="carousel-inner">
                    <div class="carousel-item active">
                      <img class="d-block w-100" src="" alt="First slide">
                    </div>
                    <div class="carousel-item">
                      <img class="d-block w-100" src="" alt="Second slide">
                    </div>
                    <div class="carousel-item">
                      <img class="d-block w-100" src="" alt="Third slide">
                    </div>
                    <div class="carousel-item">
                      <img class="d-block w-80" src="" alt="Fourth slide">
                    </div>
                  </div>
                </div>
            </div>

<div *ngIf="collection === 'Boudoir'"class="img-row picsRow">
    <li class="img-column pics">
      <img class="gallery" src="" (click)="CarouselChange(1)">
      <img class="gallery" src="" (click)="CarouselChange(2)">
      <img class="gallery" src="" (click)="CarouselChange(3)">
      <img class="gallery" src="" (click)="CarouselChange(4)">
    </li>
  </div>

component.ts

  @ViewChild('carousel') carouselElementRef: ElementRef;

  CarouselChange(index) {
    console.log(index);
    console.log(this.carouselElementRef.nativeElement);
  }

Answer №1

If you're working with Bootstrap in Angular, consider using NG-Bootstrap, a convenient Angular library designed specifically for this purpose. It offers a more streamlined approach compared to directly manipulating the DOM.

NG-Bootstrap even provides support for the Bootstrap Carousel component, which you can explore further here:

If you prefer customizing the carousel functionality yourself, you'll need to handle the "active" CSS class for the carousel items.

While a basic implementation like the one below can set you on the right path, keep in mind that the Bootstrap carousel offers additional features beyond simply displaying and hiding specific slides:

Sample code for your component.ts file:

currentIndex: number = 1;
CarouselChange(index) {
    this.currentIndex = index;
}

Your template snippet:

<!-- Carousel -->
            <div *ngIf="collection === 'Boudoir'" class="card img-row ">
                <div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
                  <div class="carousel-inner">
                    <div class="carousel-item" [class.active]="currentIndex === 1">
                      <img class="d-block w-100" src="" alt="First slide">
                    </div>
                    <div class="carousel-item"  [class.active]="currentIndex === 2">
                      <img class="d-block w-100" src="" alt="Second slide">
                    </div>
                    <div class="carousel-item"  [class.active]="currentIndex === 3">
                      <img class="d-block w-100" src="" alt="Third slide">
                    </div>
                    <div class="carousel-item"  [class.active]="currentIndex === 4">
                      <img class="d-block w-80" src="" alt="Fourth slide">
                    </div>
                  </div>
                </div>
            </div>

<div *ngIf="collection === 'Boudoir'"class="img-row picsRow">
    <li class="img-column pics">
      <img class="gallery" src="" (click)="CarouselChange(1)">
      <img class="gallery" src="" (click)="CarouselChange(2)">
      <img class="gallery" src="" (click)="CarouselChange(3)">
      <img class="gallery" src="" (click)="CarouselChange(4)">
    </li>
  </div>

For improved flexibility, consider iterating through items in your template dynamically or leveraging the NG-Bootstrap library for a more robust solution.

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

Ways to dynamically link a JSON response object to an entity?

In my ng2 implementation, I have a user.service.ts file that calls a REST service and returns JSON data. The code snippet below shows how the getUser function retrieves the user information: getUser(id: number): Promise<User> { return this.http. ...

What is the best way to sort an array of objects based on their properties?

I am working with an array of objects: let response = [{"id": 1, "name": "Alise", "price": 400, "category": 4}]; In addition to the array of objects, I have some arrays that will be used for filtering: let names = ["Jessy", "Megan"]; let prices = [300, ...

Is it possible to customize the default typography settings for Textfields and other components using a theme in Material UI v5?

Is there a method to customize the default typography for TextField and all inputs using themes? I am aware of this approach: components: { MuiInput: { styleOverrides: { root: { fontSize: '16px', ...

Changing the baseHref for ng serve in the latest version of Angular 14

My angular.json file has a set "baseHref" to '/bui' for deploying static files. However, when using ng serve on port 4200 and navigating to https://localhost:4200, I receive the message: Cannot GET / This issue is caused by the baseHref configur ...

Dealing with errors within nested requests while using switchMap with RxJS

I am faced with a situation where I need to make 2 dependent API calls: the getCars call requires the user id obtained from getUser. There is a possibility that a user may not have any cars, resulting in a 404 error from the API. How can I handle this sc ...

How can I identify the nearest ancestor based on a specific class in Angular 8?

In order to achieve a specific goal, let's imagine this scenario: Object A Object B Object C Object D Object D represents my angular component. It is important for me to adjust its height based on the heights of Object A and Object B. Regardle ...

Issues with relocating function during the NgOnInit lifecycle hook in an Angular 2 application

Currently, I am facing an issue with my Angular 2 app where the data sometimes lags in populating, causing a page component to load before the information is ready to display. When this happens, I can manually refresh the page for the data to appear correc ...

Error occurs in Typescript when attempting to store data in a record using a pointer

When working with nodes and organizing them into a tree structure, I encounter an issue: This is the definition of the interface: interface IDataObj { children: IDataObj[], frontmatter : { type: string, title: string, path: string}, name: str ...

What steps can I take to enhance the responsiveness and overall performance of this code using bootstrap?

Struggling with making your website responsive? No worries, we've all been there. Whether you're a pro at coding in react.js and vue.js or a complete beginner, we all need to start somewhere. Any suggestions or tips on how to improve responsivene ...

"NameService is not provided in Angular, please check your module

I've been struggling with loading a class into my Angular component. I've spent quite some time trying to figure out the solution, even attempting to consolidate everything into a single file. Here is what I have: Application.ts /// <referenc ...

Discovering the root cause of performance issues in a v14 Angular application

I am currently working on a web application built with Angular 14. During my testing with Lighthouse, I have discovered that the performance of the application is satisfactory on desktop but falls short for mobile users. The application consists of three ...

Find all Mondays occurring within a specified date range using Moment.js

I need to extract all Mondays within a specific date range. let start = moment(this.absence.FromDate); let end = moment(this.absence.ToDate); The user has the option to deactivate certain weekdays during this period by setting booleans. monday = true; t ...

angular-universal | firestore-admin | code: 'app/invalid-authentication' | connection timeout

import * as admin from 'firebase-admin'; var serviceAccount = require('./keys/keyfile.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "https://test.firebaseio.com" }); var registrationT ...

Is it possible to enter NaN in Vue3?

Is there a way to handle NaN values and keep a field blank instead when calculating margins with a formula? https://i.stack.imgur.com/JvIRQ.png Template <form> <div class="row"> <div class="mb-3 col-sm ...

When using Angular, automatically shift focus to the next input field by pressing the

I am faced with a challenge involving multiple editable inputs on my screen. Alongside these editable inputs, there are buttons and disabled inputs present. The current behavior is such that when I press Tab, the focus shifts to the HTML elements between ...

How can you add a Git submodule without specifying a URL?

I am looking to integrate my Angular folder as a submodule into my primary directory. The Angular folder has already been initialized as a git repository. It is currently a local folder on my Windows machine with no URL. After successfully initializing gi ...

Disregard any unrecognized variables associated with the third-party package

I've been working on integrating the bluesnap payment gateway into a react/ts project. I added their hosted javascript code to my public/index.html and started the integration within a component. However, when compiling, an error pops up saying ' ...

ag-grid angular - update group row when selection changes

After thoroughly reviewing the documentation and API references, I have not found a method to initiate a refresh on a group row when a selection change is made to its children. In my current project using ag-grid in Angular 7, I am utilizing a custom rend ...

Make the card change to gray when clicked using Bootstrap

Is it possible to achieve a common function in an infinite list using HTML, CSS, JS, jQuery (on the user's side) where an item will be grayed out after being clicked? How can we implement this effect? 1.) When the user clicks on the card element htt ...

Unable to load the node modules

In my development journey, I created an ASP.NET MVC project using Angular 2 in Visual Studio 2017 and set up node for package management. Here is a snippet from the package.json file: { "version": "1.0.0", "name": "asp.net", "private": true, ... ...