Limit the number of rows displayed with ngFor

I have an array in Angular and I am using *ngFor to display its items. I would like the items to be arranged in 2 rows with as many columns as possible. It's fine if only 6 items are displayed on the screen.

.item {
  width: 150px;
  height: 300px;
  background-color: pink;
}
<div *ngFor="let item of [1,2,3,4,5,6,7,8,9,10]">
  <div class="col item">{{item}}</div>
</div>

Answer №1

When dealing with two fixed-size rows, you can achieve the layout using absolute positioning.

<div class="wrapper">
<ng-container *ngFor="let item of items;let i=index">
  <div class="item" [ngStyle]="style[i]">{{item}}</div>
</ng-container>
</div>

The code:

items = [1, 2, 3, 4, 5, 6, 7, 8, 9];

//if 1 2 3 4 5
//   6 7 8 9
style = this.items.map((_, index) => {
  const top = Math.floor((2 * index) / this.items.length);
  const left = index % Math.floor((this.items.length + 1) / 2);
  return {
    top: top ? top * 300 + 'px' : 0,
    left: left ? left * 150 + 'px' : 0
  };
});

//if 1 3 5 7 9
//   2 4 6 8

style2 = this.items.map((_, index) => {
  const top = index%2;
  const left = Math.floor((index/2));
  return {
    top: top ? top * 300 + 'px' : 0,
    left: left ? left * 150 + 'px' : 0
  };
});

The .css

.wrapper{
 position:relative;
}
.item{
  position:absolute;
  width: 150px;
  height: 300px;
  background-color: pink;
}

Here is the link to StackBlitz

Update - For a simple grid layout like:

1 2 3 
4 5 6

We can use CSS flex properties (Check out this guide on CSS Flexbox)

.wrapper-flex
{
  display:flex;
  flex-direction:row;
  flex-wrap:wrap;
  height:204px;
  width:100%; //<--necessary for pagination
  overflow:hidden;
}
.wrapper-flex .item{
  position:relative
}

You need to set the height of the wrapper and use overflow hidden.

Introducing variables "page", "page-size" (and "numPages") allows for pagination

I'm using a template reference variable "wrapper" in a ViewChild, and subscribing to the window.resize event in ngAfterViewInit

  page=0;
  pageSize=this.items.length;
  numPages=1
  ngAfterViewInit(){
    setTimeout(()=>{
    fromEvent(window,'resize').pipe(
      startWith(null)
      ).subscribe(_=>{
        const width=this.wrapper.nativeElement.getBoundingClientRect().width
        this.pageSize=Math.floor(width/150)*2;
        this.numPages=Math.floor(this.items.length/this.pageSize)
        this.page=0;
      })
    })
  }

NOTE: The StackBlitz has been updated with these changes

Answer №2

To achieve this layout using CSS Grid, you can follow these steps:

.item {
  width: 150px;
  height: 300px;
  background-color: pink;
}

:host {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  grid-template-rows: 1fr 1fr;
  grid-gap: 20px;
}

With this code, the content will be arranged in 2 rows dynamically depending on screen size. If the items have a fixed width of 150px, on smaller screens they will expand to additional rows to accommodate all the content. You can test this by resizing the window.

For a live demonstration, check out the example here: https://stackblitz.com/edit/angular-ivy-zuvpxg?file=src/app/hello.component.css

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

Dynamically modifying the styling of elements within an iframe

In my current project, I encountered a challenge with changing the background color to black and the body text color to white within an iframe. Additionally, all elements that are originally styled with black in an external stylesheet also need to be chang ...

Issue with Bootstrap card "sub-components" such as card-heading not functioning

I'm facing an issue while trying to integrate BlazorStrap into an existing .NET6 Blazor web assembly app. It seems like there is a problem with Bootstrap that needs to be resolved before I can get BlazorStrap to function properly. Let's focus on ...

Image resizing on the fly

Can dynamic image resizing be achieved through CSS or does it require HTML coding? ...

Analyzing CSS transform values for rotate3d utilizing regular expressions

I want to split css transform values into an array, while keeping rotate values grouped together. For instance: 'translate3d(20px, 5px, 10px) rotateX(20deg) rotateY(10deg) rotateZ(0deg) skew3d(20deg, 10deg) rotateX(-20deg) rotateY(100deg) rotateZ(-3 ...

A step-by-step guide on toggling between light mode and dark mode using water.css

Implementing the water.css on my website, I have this JavaScript code: function setTheme(themeName) { localStorage.setItem('theme', themeName); document.documentElement.className = themeName; } // function to toggle between light and dark ...

Add HTML content to a specific div according to the option selected in a drop-down menu

I am currently working on a project where I need a button to insert HTML content into a div based on the value selected in a select box. However, the functionality is not working as intended. Upon clicking the button, nothing happens. I am unsure of what t ...

Modifying CSS files in real-time

I've been attempting to dynamically change the CSS file, but I've run into an issue: Whenever I try to alter the style, it seems to work correctly while in "debug mode", showing that the changes are applied. However, once the JavaScript function ...

Tips on sending a form to the server with ajax technology

I'm struggling with sending a button id to my server through ajax in order to submit a form without having to constantly reload the page every time I click on a button. Unfortunately, it's not working as expected and I can't figure out why. ...

Having trouble with flickering in rotating card animation in Bootstrap using CSS?

Recently, I worked on a bootstrap website where I implemented a unique feature – a card that flips to show its backside upon hover. You can check out the live website here: Live Site Here's the code snippet for the section with the flipping card: ...

Validator checking the status of an Angular form

Currently working on developing a custom form validator. In my test component, there are three checkboxes. The main form should only be considered valid if at least one checkbox is checked. https://stackblitz.com/edit/stackblitz-starters-69q3rq Within th ...

The malfunction of CSS3 effect

I designed a website and used DIV CSS to call an image. .header_bottom_area { background: url(../img/HomepagePanels.jpg)no-repeat scroll center center; max-width: 100%; width: auto; height: 911px; } I would like to have the same image as shown in ...

Why isn't the CSS pseudo ::before functioning properly on an Icon element?

I am encountering an issue with displaying a vertical line to icons in my HTML code. The structure of the HTML is as follows: Below is the HTML code snippet: <div class="newsTimePeriod item-One"> <h3>News</h3> ...

Can responsive images be utilized with a DIV's background-image property?

For my website, I want to incorporate a variety of Thumbnails that are retrieved from a database and displayed in different sizes within a Masonry grid. Typically, I would use background-image:url(image.jpg); background-size: 100% 100%:, but I am aiming t ...

Utilizing Smarty Template: Combining <li> elements from separate <ul> tags for a seamless display

On my Prestashop website, I have implemented the "Advanced Homepage Product List" module. I removed the category names from the titles to have my items sorted without displaying the category names. Currently, this is how it appears: https://i.stack.imgur. ...

Stop child components from rendering until the parent controller has successfully resolved the data

My current scenario is as follows: I have an app.module that bootstraps the app.component The router in my application has a base href = '/' This router loads my home.component, which contains an onInit() method to fetch data from an API using ...

Utilizing JavaScript for parallax horizontal scrolling (identifying optimal 50% of screen)

I have successfully implemented this code for vertical scrolling: $('.flapleftclass').css('top',(0+(scrolled*0.5))+'px'); This method works well because I am referencing to the top position. However, when it comes to horizon ...

Splitting the text vertically by utilizing a single DOM element

I am searching for a way to split my text vertically, with line breaks so that only one word should be present on each line. Currently, I have achieved this by using separate DIV elements for each word. Is it possible to accomplish the same layout using ...

The height attribute is not functioning properly in Mozilla Firefox

I am facing an issue on my website where I set the height of the body tag to 1460px. It works perfectly on Chrome and IE, but there are problems on Firefox. See my code below: body { background-image: url('../images/background.jpg&apos ...

Creating a table and filling it with data from any cell is a simple process

I have a question about creating an HTML table similar to the image shown here: image I want to populate the table with data from a JSON response received from a web service: { "ErrorCode": 0, "ErrorMessage": "ok", "Data": [ { ...

Extract information from the website "angular.callbacks" using web crawling techniques

Looking to utilize R for scraping news from the following URL: "AlphaGo"&ss=fn&start=0). Below is the code I am working with: url <- "http://api.foxnews.com/v1/content/search?q=%22AlphaGo%22&fields=date,description,title,url,image,type,taxo ...