Creating custom Bootstrap Card Groups by dynamically generating the specified number of cards with Angular directives

I am currently using Angular 9.1.8 for my project.

For my Angular component, I have implemented Bootstrap Card Groups and Cards to display a large result set of cards in rows with more than two cards per row. Below are four example cards:

<div class="container">
  <div class="card-group">
     <!-- card 1 -->
    <div class="card bg-light text-dark">
      <img class="card-img-top" src="../../assets/trucking_placeholder2.png" alt="Card image">
      <div class="card-body">
        <div class="row">
          <div class="col">
           <h6 class="card-title"> <i class="fas fa-circle text-success"></i> ABC Truck Repair</h6>
          </div>
          <div class="col">
            <div class="float-right"&g;$75/hr | 2.6 miles</div>
          </div>
        </div>
      </div>
        <p class="card-text">123 Main Street Idaho Falls, ID 83401</p>
        <a href="#" class="card-link"><i class="fas fa-phone-alt"> 208-970-9341</i></a>
      </div>

...

While trying to achieve this layout, I tried using the *ngFor directive as shown below:

<div class="container">
  <div class="card-group">
     <!-- card 1 -->
    <div *ngFor="let s of shops;" class="card bg-light text-dark">
      <img class="card-img-top" src="../../assets/trucking_placeholder2.png" alt="Card image">
      <div class="card-body">
        <div class="row">
          <div class="col">
           <h6 class="card-title"><i class="fas fa-circle text-success"></i> {{s.name}}</h6>
          </div>
          <div class="col">
            <div class="float-right">${{s.laborRate}}/hr | 2.6 miles</div>
          </div>
        </div>
      </div>
        <p class="card-text">{{s.address}}<lt/p>
        <a href="#" class="card-link"><i class="fas fa-phone-alt"> {italic}{{s.phone}}</i></a>
      </div>

...

However, I found that this approach did not limit each group to only two cards as desired.

If you know how to achieve displaying only two cards per group using Angular directives, or if there is a better method to accomplish this, please let me know!

Answer №1

Once you have gathered your information, consider structuring it into a two-dimensional array containing pairs of cards within each array element. To display this data in HTML, utilize two *ngFor directives: the first loop will generate your card-groups, while the second loop will fill in the individual card details for each pair.

Answer №2

After encountering some difficulties, I realized that relying solely on Bootstrap wouldn't solve my issue. To overcome this roadblock, I made the decision to remove the *ngFor angular directive from the card groups. By utilizing basic CSS Grids, I successfully achieved a two-column layout effortlessly by implementing the steps outlined below:

To begin, I assigned the class .grid-container to the parent container containing my cards.

<div class="container grid-container">
  <div *ngFor="let s of shops;" class="card bg-light text-dark">
    <img class="card-img-top" src="../../assets/trucking_placeholder2.png" alt="Card image">
    <div class="card-body">
      <div class="row">
        <div class="col">
          <h6 class="card-title"> <i class="fas fa-circle text-success"></i> {{s.name}}</h6>
        </div>
        <div class="col">
          <div class="float-right">${{s.laborRate}}/hr | 2.6 miles</div>
        </div>
      </div>
    </div>
    <div class="card-body">
      <p class="card-text">{{s.address}}</p>
      <a href="#" class="card-link"><i class="fas fa-phone-alt"> {{s.phone}}</i></a>
    </div>
  </div>
</div>

Subsequently, I incorporated the following CSS styles:

The display: grid property indicates the utilization of CSS Grids. The

grid-template-columns: auto auto;
specifies a two-column layout where dimensions are determined by each child element. (Bootstrap handles the styling for individual cards in my scenario)

For responsiveness, I included a media query that triggers when the screen size falls below 600px, transitioning to a single-stretched out column layout inherited from Bootstrap which functions effectively on mobile devices.

.grid-container {
  display: grid;
  grid-template-columns: auto auto;
}

@media (max-width: 600px) {
  .grid-container {
    display: inherit;
    grid-template-columns: inherit;
  }
}

It was as simple as that. While Card Groups were beneficial for styling, they introduced unnecessary complexity when generating cards dynamically.

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

What's the point of specifying position relative if it's not even needed?

Why do I see many sites setting the position: relative; in block elements when they do not use position in the inner elements? Is there any other reason to set the position relative? For example: <div class="parent"> <div class="parent__contai ...

Encountering a 404 error when trying to navigate to the next route using the Link component

Having issues with my login route. I've added a Link to the login route inside a button tag in my Navbar component, but when I try to access the route, I'm getting a 404 error page. --app ----pages ------component --------Navbar.js ----- ...

How can I transfer CSS styles from one class to another using JQuery?

Is it possible for me to create a timepicker that matches the style of the datepicker in the current UI Theme? I am looking to replicate the CSS properties from the datepicker for my timepicker without copying any behavioral aspects. (Although there are o ...

Enforcement of Typescript Field Type Lax During Assignment

My current issue involves a constructor that is supposed to set the value of _device. The field is specifically designed to be of type number, and the constructor parameter is also expected to be of type number. However, when a parameter of type string is ...

Angular Testing: Discovering the best practices for asserting expectations post function execution

I'm currently facing a challenge while unit testing my Angular application. I need to make an HTTP call on a local file, but the expects of the test are getting called before and after the HTTP call, causing it to crash. How can I resolve this issue? ...

Interacting with API using Ajax and jQuery

I am struggling to get my simple jQuery request to work correctly. I'm not sure what I'm doing wrong. Can you help me identify the error? http://jsfiddle.net/k6uJn/ Here is the code snippet: $(document).ready(function() { $.ajax({ type: "G ...

Leveraging animations in Angular2 that are defined outside of a component

I've recently put together a basic component @Component({ selector: 'saved-overlay', templateUrl: './saved-overlay.html', exportAs: 'saved-overlay', animations: [ trigger('inOut', [ transition ...

Error: Express.js failing to send the correct file in response

For some reason, express.js seems to be acting strangely when I try to send an HTML file in a GET request. const express = require("express"); require('dotenv').config() const app = express(); const PORT = process.env.PORT || 5000; ap ...

Issue with Angular not rendering data retrieved from HTTP response

In my Service script class, I have defined a HomeApiService with the following code: export class HomeApiService{ apiURL = 'http://localhost:8080/api'; constructor(private http: HttpClient) {} getProfileData():Observable<HomeModelInterface[ ...

Issue with Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object'. NgFor is only compatible with binding to Iterables such as Arrays

As someone who is new to Angular, I am facing a challenge while working on my portfolio project. The issue arises when trying to receive a list of nested objects structured like this: "$id": "1", "data": { &quo ...

Refresh the HTML page following a jquery click event

One of my onclick functions is designed to return sorted data in a specific format when triggered. Here's the code snippet for this function: $(document).ready(function () { $(".feedbackClick").click(function () { $.post("/Analyze/GetSorte ...

Positioning CSS for a Responsive Button

Currently, I am working on making my modal responsive. However, I am encountering an issue with the positioning of the "SAVE" button. The button is not staying in the desired position but instead disappears. Below is the snippet of my HTML and CSS: .dele ...

Having trouble with CSS text not wrapping correctly?

While working on a web application, I encountered an issue where the text within a <div> element on my page was not wrapping properly and instead overflowing outside the box. The <div> in question goes through two stages: one where it is not e ...

I recently started exploring the world of creating discord bots using node.js, and I'm currently facing a bit of a challenge with it

As a beginner in the world of creating discord bots, I am currently focusing on developing commands. I recently followed a tutorial on Youtube which guided me through the process. The tutorial instructed me to use the following code snippet: const prefix ...

Tips for clearing the browser cache when working with AngularJS in HTML code

Does anyone know how to clear the browser cache in HTML when using AngularJS? I've tried adding the following code to my index.html file and also used $templateCache in my app.js without success. <meta http-equiv="Cache-Control" content="no-cache, ...

Load the entire AngularJS webpage using AJAX requests

I'm facing a challenge where I need to integrate an entire legacy page, along with some AngularJS elements, into our new page using AJAX. Initially, all I could see was the raw AngularJS markup: Rank ID {{$index+1}} {{player.playerid}} Afte ...

Leveraging the select class in Flask

In my Python application, I am trying to extract the selected value from an HTML/JavaScript form. Below is the snippet of my HTML code: {% block content %} <form method="post"> <div class="form-group"> <label f ...

Enhance the <div> with interactive content through dynamic updates on click within the same element

I am currently developing an Editor-Menu for a website administration. When I open admin.php, the Editor-Menu should be loaded into the #ausgabe div using the code $('#ausgabe').load('./admin-ajax/ajax2.php'). This functionality is work ...

Strategies for Effective CSS Footer Placement

In the demo, you can see that my footer bar is not in the correct position. I am having trouble figuring out why the footer is not settling after the content div. Ideally, the footer should be right after the article. I tried searching for specific keyword ...

Tips for waiting for the onChange event before setting the Value with react hooks

When trying to retrieve the current value of the state variable value within the handleKeyDown function, it seems to always display the previous state instead of the most recent input. To address this issue, a setTimeout was implemented to ensure that hand ...