ngFor displaying items in a stacked layout within a flexible carousel

Incorporating Angular 11 along with the https://www.npmjs.com/package/angular-responsive-carousel responsive carousel has been a part of my project. The carousel is filled with mat-cards through an array. However, upon initially loading the page, all the cards seem to overlap each other as displayed here

Here's how it should ideally appear: this

Interestingly, resizing the window and then reverting it back to its original size makes the carousel render correctly. I am in search of a solution that ensures the correct rendering of cards right from the beginning.

The HTML code snippet is structured like this:

<carousel [dots]="true" [cellsToShow]=cellsToShow [height]="carouselHeight" [autoplay]="false"
        [autoplayInterval]="2000"
        [borderRadius]="2" [pauseOnHover]="true">
<div class="carousel-cell" *ngFor="let item of cards; index as i; trackBy: fun">
  <mat-card class="example-card mat-elevation-z0">
    <mat-card-header>
      <a mat-card-avatar class="example-header-image" [href]="telegramUrl" target="_blank"</a>
      <mat-card-title><b>Latest Offers</b></mat-card-title>
      <mat-card-subtitle><i>From Nerd Deals</i></mat-card-subtitle>
    </mat-card-header>
    <br>
    <div class="example-card-image"><img mat-card-image [src]=item[0] alt=""></div>
    <mat-card-content>
      <div [innerHTML]="item[1]"></div>
      <br>
      {{item[2]}} <a href="{{item[3]}}" target="_blank">{{item[3]}}</a>
    </mat-card-content>
  </mat-card>
</div>

The corresponding CSS section appears as follows:

.carousel{
  position: relative;
  z-index: 1;
  padding-left: 10%;
  padding-right: 10%;
}

.carousel-cells{
  height: auto !important;
}

.carousel-cell{
  height: auto !important;
}

.example-card {
  max-width: 70vw;
  text-align: left;
  overflow-wrap: break-word;
  height: auto !important;
  border-style: solid;
  border-width: thin;
}

Answer №1

My suggestion is to include cdRef.markForCheck() in the ngAfterViewInit() lifecycle hook of the component that utilizes the carousel:

import { Component, AfterViewInit, ChangeDetectorRef } from '@angular/core';

@Component({
  ...
})
export class MyComponent implements AfterViewInit {
  constructor(private cdRef: ChangeDetectorRef) {}

  ngAfterViewInit(): void {
    this.cdRef.markForCheck();
    // alternatively, try using this.cdRef.detectChanges(); instead
  }
}

It's even more effective to trigger change detection as soon as the data for the carousel is ready.

Answer №2

The reason behind this issue is that the carousel starts rendering before the data is actually added to the cards. As a result, the carousel cells do not adjust to the actual width inside the carousel due to lack of data during rendering.

Fortunately, there is a straightforward solution to fix this problem. Simply provide a default width for the carousel cells by including the 'cellWidth' attribute in the package. Refer to the code snippet below for implementation.

<carousel [cellsToShow]=5 [cellWidth]=250 [arrows]=false>
      <div> Your content </div>
 </carousel>

Furthermore, since the attribute supports property binding, it is possible to set the cell widths based on screen size using TypeScript. Although I haven't personally tested this approach, the above code worked successfully for me on a laptop screen.

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

Transform an array of dates containing time zones into Coordinated Universal Time (UTC) or Greenwich Mean Time (

So, I am facing an issue with a plugin that generates an array of dates without the ability to modify it. This plugin is embedded in the app's core and pulls data from a central database. The problem lies in the fact that the array of dates includes ...

The webpage is drifting sideways to the right without any content being displayed

Recently, I launched a new website and encountered an issue with a static page I designed. While it may not be a critical problem, it is certainly bothering me! If you want to check out the website in question, visit: In essence, I have used CSS to hide ...

Currently, I am delving into the world of website development with nodejs, express, mongoose, and handlebars. I am facing a challenge with removing a response to a comment

I've been working on a website project that allows users to post blogs, comment on blogs, and reply to comments. I've encountered an issue with deleting replies from the server side code: // Handle submission of comments or replies app.post(&apos ...

Best practice for resetting jquery datatables for proper functioning

A user on Stack Overflow was seeking a solution for working with DataTables.js and a variable number of columns. The provided solution can be found here: http://jsfiddle.net/gss4a17t/. It's worth noting that this solution relies on a deprecated funct ...

Search for information containing the keyword "mongo" within multiple related datasets

Since mongodb lacks support for join operations and I need to search across multiple business collections, services, and users, I have devised a solution that requires validation and possible improvements. The proposed schema flow is as follows: Business ...

Upgrade your function to utilize Firebase V9 with Next.js framework

I recently updated my project to use version 9 of firebase, and since then, I've been encountering some code errors that I'm struggling to resolve. The previous function had the following structure, but now I need to update it to work with the n ...

Using Vue: Triggering .focus() on a button click

My journey with vue.js programming started just yesterday, and I'm facing a challenge in setting the focus on a textbox without using the conventional JavaScript method of document.getElementById('myTextBox').focus(). The scenario is that i ...

collection of random header images for a ruby on rails website

Can anyone help me with an issue I'm having? I am trying to randomize images in a header on a category page using the following code, but it doesn't seem to be working. I keep getting this error: Invalid CSS after "...ackground: url(": expected " ...

The method item.appendChild does not exist as a function

Despite being a common error, I've researched extensively and still can't figure out why it's happening. It seems like it should be an easy fix, but I'm struggling to find the solution on my own. var item = document.createElement("div" ...

Exploring the functionality of angular reactive forms in creating intricate JSON structures

After numerous attempts to resolve the issue on my own, I am reaching out to an Angular developer for assistance. My goal is to display a JSON object in the UI: Here is the JSON Object : items={"departure":"New York","arrival":"California","stations":[ ...

Unable to access property 'runnable' of null while running Jest test

After creating a new .spec file, I encountered an issue where the tests inside it are failing with the following error: TypeError: Cannot read property 'runnable' of null at ret (node_modules/selenium-webdriver/testing/index.js:175:25 ...

Tips for maintaining space beneath an image when text wraps around it

.blogimgarea { width: 38%; padding-right: 26px; float:left; } img{max-width:100%} .blogtextarea { width:55%; padding:22px 32px 0 0; float:right; } <div class="newpostregion pt70"> <div class="blogimgarea"> <img class="featblogimg" src="https ...

Modifying the Hover Color of the Navbar in Bootstrap 4: Tips and Tricks

Looking to customize the hover color of my navbar but struggling to find the right element in the inspect tool. Tried solutions from Stack Overflow with no luck, any suggestions would be appreciated! <!doctype html> <html lang="en> <hea ...

Show the id value of the event triggered by eventclick

I am currently attempting to retrieve the id of the event so that I can remove it from the database. My approach involves using eventClick, where a dialog pops up when the user clicks an event prompting them to remove it. In order to proceed with this oper ...

Adjusting the transparency of my banner background image using Bootstrap 4

How can I make the background image transparent without affecting other elements like the navigation menu and main text? After researching online, I discovered that overlaying with a white image of the same size could be the solution. However, when attem ...

While employing Angular 7, I encountered an issue where the routerLink fails to function when I attempt to click on the anchor button

Within Angular 7, I have created various components within the app folder and defined them in the routing as well. When I specify the router name in the URL, it works perfectly by displaying the component attached to that URL. However, when I define the ro ...

hiding the search box by clicking away from it

Can someone help me with modifying this search box design? @import url(http://weloveiconfonts.com/api/?family=entypo); /* entypo */ [class*="entypo-"]:before { font-family: 'entypo', sans-serif; color: #C0C0C0; } * { margin: 0px; pad ...

How to toggle checkboxes with jQuery

One issue I am facing is with a list of checkboxes within my Kendo grid. I have a select all option available as well. The problem arises when I select all checkboxes, then manually unselect some of them, and finally try to save the selection. The grid dis ...

the deactivation of my rollover class is being caused by my float class

With the assistance of a generous contributor on stackoverflow, I was able to overlay different colored CSS boxes onto various images. These boxes could be removed upon mouseover, revealing the images beneath. You can view the code I used on fiddle here. ...

Ways to prevent image toggling when the mouse moves out of it or when the hover effect stops

I'm looking to toggle between two images on mouseover/hover and stop the toggling when hovering stops. Here is the HTML code I have: <div class="fader"> <img src="image1" /> <img src="image2" /> </div> This is the JQuery ...