Angular2 with Bootstrap Grid integration is a powerful combination for building

Struggling to implement bootstrap's grid layout system in Angular2 with a list of objects. Any tips or guidance would be greatly appreciated!

If I was using HandlebarsJS, I could achieve this layout with the following code:

{{#for elements}}
    {{#if index % 12 === 0}}
          <div class="row">
    {{/if}}
    <div class="col-md-2">
          {{element.name}}
    </div>
    {{#if index % 12 === 0}}
          </div>
    {{/if}}
{{/for}}

Desired output:

<div class="row">
    <div class="col-md-2">
        Bob
    </div>
    <div class="col-md-2">
        Joe
    </div>
    ...
</div>
<div class="row">
    <div class="col-md-2">
        Julie
    </div>
    <div class="col-md-2">
        Cheryl
    </div>
    ...
</div>

Answer №1

Delving into an age-old discussion, this time focusing on the latest version of Angular. If you're seeking innovative solutions for a similar query in Angular 1.x, do check out some insightful ideas here that can be tweaked to suit your current needs. Personally, I lean towards Duncan's approach, though preferences may vary. Below is a revamped rendition of his code tailored for Angular2 displayed elegantly on Codepen:

  <div class="row">
    <div *ngFor="let hero of heroes; let i = index">
      <div class="clearfix" *ngIf="i % 3 == 0"></div>
      <div class="col-md-4">{{hero.name}}</div>
    </div>
  </div>

Check Out Codepen Example

Codepen Tip: The blue background signifies the row, while the red represents the col-md-* cell.

Observing the structure, you'll notice that all col-* elements are enclosed within a single row element, with a clearfix added every few iterations. In my opinion, this method offers a neat and sleek layout resembling something along the lines of Google Material Design Lite (MDL)-inspired grid setup rather than conforming strictly to Bootstrap norms.

While these solutions might not align precisely with your initial request, it's akin to comparing apples and oranges, each presenting its unique flavor.

Answer №2

Dealing with a similar challenge, we encountered the task of creating a list that could seamlessly switch between list and grid styles. One effective approach to implementing the grid style using bootstrap and angular 2 is by transforming the input array to suit the grid row/col structure.

To achieve this, you can generate a two-dimensional array of rows based on the desired number of columns. The example provided below showcases a fully dynamic version.

We trust that this solution will be beneficial to your project...

Component code:

export class Component implements OnChanges {

    @Input() items: any[] = [];
    @Input() gridCols: number = 4; // Define the number of columns in the grid
    private gridItems: any[][];
    private gridValidValues = [1, 2, 3, 4, 6, 12]; // Values divisible evenly for column count

    private initGrid() {
        this.gridCols = this.gridCols | 0; // Convert to integer
        this.gridCols = this.gridCols || 1; // Ensure at least one row

        if(!this.gridValidValues.find(value => this.gridCols === value)) {
            this.gridCols = 4; // Adjust invalid input to default column count
        }

        let addition = this.items.length % this.gridCols > 0 ? 1 : 0;
        let rows = ((this.items.length / this.gridCols) | 0) + addition;

        this.gridItems = [];

        let index = 0;
        for(var i = 0; i < rows; i++) {
            let row: any[] = [];

            for(var j = 0; j < this.gridCols && index < this.items.length; j++) {
                    row.push(this.items[index]);
                    index++;
            }

            this.gridItems.push(row);
        }
    }

    ngOnChanges(changes: SimpleChanges): void {
        let itemsChange: SimpleChange = changes["items"];

        if(itemsChange) {
            let previous: any[] = itemsChange.previousValue;
            let current: any[] = itemsChange.currentValue;

            if(previous.length != current.length) {
                this.initGrid();
            }
        }
    }
}

Template code:

<div class="row"
     template="ngFor let row of gridItems">
    <div bind-class="'col-md-' + (12 / gridCols)"
         template="ngFor let item of row">
        {{item.anyvalue}}
    </div>
</div>

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

Tips for Preventing Unnecessary Ajax Requests

What I require When a click event is triggered, a service call should be made only once. Use case Dropdown1 Dropdown2 Dropdown3 1. There are three dropdowns on the HTML page. 2. When Dropdown1 is called - an AJAX call is made only onc ...

Halt the iteration process and confirm a true result upon discovering a match between two arrays

I have two databases, one stored in indexedDB and the other in PouchDB (even though I am aware that PouchDB is built on top of indexedDB). The dataset in indexedDB contains a list of rooms, which was saved through a previous page and is now being displaye ...

AngularJS ui-router behaving erratically when manually refreshing the page

While working on an application with my team, we've noticed some inconsistent behavior. When a user refreshes the browser, the page UI state is fully refreshed, but only up to a certain route. Our application starts on the /Home route, establishing t ...

Is there a way to consistently determine if the focus is currently activated? (Using Javascript and jQuery)

I am completely new to the world of Javascript and jQuery, and my JSFiddle is really showcasing the issue perfectly. http://jsfiddle.net/mkLsr/3/ My main goal is to have a search box text input automatically focused when the page loads, allowing users to ...

button behavior based on the currently visible section

Hey there, I'm new to this! I usually come here to find solutions, but I'm stuck right now. I have a single-page website with different sections. I've created a function to switch between these sections, showing one at a time and hiding the ...

The functionality of the Angular Bootstrap btn-radio remains unchanged despite efforts to modify its

I am facing an issue with my HTML code: <label class="btn btn-sm btn-info" ng-model="radioModel" btn-radio="'title'"><i class="fa fa-check text-active"></i> Jobprofil</label> <label class="btn btn-sm btn-success" ...

Struggling to manage the flow of my program, constantly switching back and forth between handling AJAX callbacks and rendering PIXI

I'm struggling with optimizing the flow of my JavaScript script. The script is responsible for receiving and sending mouse coordinates to be drawn. Take a look at the code snippet below: //Initializing PIXI var stage = new PIXI.Stage(0x000000); var ...

Exporting multiple classes from different scripts in NodeJS can be achieved by using

Consider the following setup: script1.js class A{ constructor(){ this.name = "A" } } script2.js class B { constructor(){ this.name = "B" } } Now, let's look at clients.js const clientA = require('./script1'); const ...

Using the Angular Material Tree to showcase the hierarchical layout of an organization's

I am looking to visually represent the structure of an organization using an angular material tree, with properties such as position, salary, and years of service for each employee. class Employee { name: string; position: string; salary: number; ...

Ways to maintain a C# list on my webpage in order to modify it on the client side

Currently working with ASP.Net MVC 3.0 and facing an issue. My model contains a telephone list that I need to preserve for later manipulation and display using jQuery in my script. I attempted to save the list in a hidden field but have been unsuccessful ...

Verify that the computer is connected to the Internet by sending an ajax request to Google

Whenever I need to test my internet connection, I rely on the following code snippet: const checkInternetConnection = () => { $('input').ajaxError(function(){ alert("failed"); }); $.get('http://www.google.com', f ...

Troubleshooting issues with document.querySelectorAll in JavaScript

Can someone explain why document.querySelectorAll isn't functioning properly in this code snippet? I'm a beginner and could use some help. <p id="demo">This is a paragraph.</p> <h1 id="1demo"> Hello </h1&g ...

The Ion-icon fails to appear when it is passed as a prop to a different component

On my Dashboard Page, I have a component called <DashHome /> that I'm rendering. I passed in an array of objects containing icons as props, but for some reason, the icons are not getting rendered on the page. However, when I used console.log() t ...

Using Javascript in n8n to merge two JSON arrays into a single data structure

When working on a project, I extract JSON objects from the Zammad-API. One of the tickets retrieved is as follows: [ { "id": 53, "group_id": 2, "priority_id": 2, "state_id": 2, "organizati ...

Implementing server-side pagination with Ngrx and using router parameters to navigate pages

In my store, I have a simplified state tree structure: { routerReducer: { state: { url: '/blog' }, queryParams: { category: 'home' } params: { } }, blog: { ...

generate a new canvas within an Angular 6 framework at a library

I am in the process of developing a unique Angular library that will enable image cropping using canvas. I initialized the library with "ng generate library" command, but when attempting to draw on the canvas, no results are visible. Here is the code from ...

Learning to utilize collection data from Firestore in Ionic Angular involves a few key steps

Angular CLI: 13.0.4 ionic --version => 6.20.2 Hey there! I'm fairly new to working with Ionic, Angular, and Firebase. I've set up my Firebase Firestore database, created a collection, and populated it with data. However, I'm struggling t ...

Tips for customizing the appearance of a leaflet popup in your own unique style

I've been attempting to style a marker popup, but for some reason, the styles aren't being applied to the popup. Additionally, I'm having trouble adding a button to the popup. import { Map, marker} from "leaflet"; const popupOptions = { ...

AngularJS textbox validation for numbers and required in repeating mode ensures that the user input is a

For more information, please visit the following link: https://plnkr.co/edit/9HbLMBUw0Q6mj7oyCahP?p=preview var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.NDCarray = [{val: '' ...

Using React to filter the "All" category based on props

I'm currently implementing filter logic on my webpage. By clicking on different buttons, I am able to filter the initial array. However, I am now facing an issue on how to display all the items in the array to a sibling component when the "All" button ...