What is the best way to divide an array into groups of four elements when using ngFor

Is there a way to divide an array into groups of four when using ngFor?

How can I display four projects at a time instead of one?

   <div *ngFor="let item of items$ | async">
     // How can I show here 4 projects instead of one?
     {{item}}
    </div>

Answer №1

If you want to display items in rows of 4, you can use the slice pipe in Angular: TS:

export class AppComponent  {
  private itemsInRow = 4;
  // creating an array of 14 integers
  private arr = Array.from(Array(14).keys());

  itemInRowRange = Array.from(Array(this.itemsInRow).keys());
  items = of(this.arr);
}

HTML:

<div class="outer" *ngFor="let i of itemInRowRange">
  <div class="box" *ngFor="let item of items | async | slice: i*4 : i*4 + 4">
    {{item}}
  </div>
</div>

Check out the example on StackBlitz

Answer №2

module:

public items: string[] = [
    "apple",
    "banana",
    "carrot",
    "date",
    "eggplant",
    "fig",
    "grape",
    "honeydew",
    "kiwi",
    "lemon"

]

layout:

<div *ngFor="let item of items; let i = index">
  <ng-container *ngIf="i % 4 == 0 || i == 0">
    {{items[i]}}
    {{items[i+1]}}
    {{items[i+2]}}
    {{items[i+3]}}
  </ng-container>
</div>

the main concept is to determine if the position of the current item in the array being looped through is divisible by 4

Answer №3

Revamp the structure of the array being utilized in the component by converting it into an array of arrays, each containing 4 elements.

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

Below is an illustration of how you can restructure the array using a loop:

const items = [1, 2, 3, 4, 5, 6, 7, 8];
const parentArray = [];
let childArray = [];
items.forEach(item => {
     childArray.push(item);
     if(childArray.length === 4){
          parentArray.push(childArray);
          childArray = [];
     }
});

Subsequently, embed another ‘ngFor’ within the first one in your template:

<div *ngFor=“let item of parentArray”>
    <div *ngFor=“let subItem of item>
        {{ subItem }}
    </div>
</div>

Although not the most elegant solution, this method aligns with your request.

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

Discovering the functionality of es6 object.assign and find methods within a typescript file

Currently, I am in the process of transitioning from Java Script to TypeScript for my project. However, I am facing limitations as I am unable to utilize object.assign() and find methods. ...

Creating an Angular interface that includes static values

How can we define an interface in Angular that includes constant values? For example, creating a 'State' interface that lists all the states in Australia. One way to do this is by defining the State interface like so: interface State { name: ...

In Angular 2, templates may not be fully executed when utilizing ngAfterContentInit or ngAfterViewInit functions

When I try to access the DOM of the document, I notice that the template is only partially executed. Using a setTimeout helps me bypass the issue temporarily, but what is the correct way to handle this? import { Component, Input, AfterContentInit } from & ...

Issue with interface result: does not match type

Hey there! I've been working on creating an interface in TypeScript to achieve the desired return as shown below: { "field": "departament_name", "errors": [ "constraint": "O nome do departam ...

Using a comma as a decimal separator for input is not permitted when working with angular/typescript/html

I am facing an issue with my Angular frontend where I have numerous html input fields that trigger calculations upon typing. <input type="text" [(ngModel)]="myModel.myAttribute" (input)="calculate()"> The problem arise ...

Transferring data from the server to the client side in Next JS with the help of getInitialProps

I am currently developing an application using nextJS. Within server/index.ts, I have the following code: expressApp.get('/', (req: express.Request, res: express.Response) => { const parsedUrl = parse(req.url, true); const { query } = ...

Tips for updating the styleurls link dynamically by clicking a button and maintaining the changes

In the midst of developing an angular 2 project, I am currently working on integrating theme settings. Within my project, I have crafted three distinct component.scss files: red.component.scss, yellow.component.scss, and blue.component.scss. My goal is t ...

An error occurred while running React, Next.js, and Type Script: Unhandled Runtime Error - TypeError: Unable to access 'value' property of undefined

I have been working on a multi-page form and using the antd package to add some styling to it. On the main page of the form, I implemented the following code (making sure I imported everything required). export class CreateNewContract extends Component ...

Troubleshooting problem with sorting in Angular 4 material header

Using Angular 4 material for a table has presented me with two issues: 1. When sorting a table, it displays the description of the sorting order in the header. I would like to remove this. https://i.sstatic.net/5bHFO.png It displays "Sorted by ascending o ...

After updating to ionic-native 2.5.1, encountering TypeScript Error TS1005 in Ionic 2

After updating to the latest version of ionic-native (2.5.1) in my ionic 2 project, I am encountering Typescript errors when running "ionic serve" in my terminal. I have attempted to update the typescript version to 2.x but to no avail. Any assistance woul ...

Dynamically determine the data type of a value by analyzing the key property within a function

I have created a custom hook that extends the functionality of the useStata function by accepting key and value props; import { Dispatch, SetStateAction, useCallback, useState } from 'react'; export type HandleModelChangeFn<T> = (key: keyo ...

Having trouble getting the onClick function to work in your Next.js/React component?

Recently, I delved into using next-auth for the first time and encountered an issue where my login and logout buttons' onClick functions stopped working when I resumed work on my project the next day. Strangely, nothing is being logged to the console. ...

Tips for presenting SVG symbols using Interpolation within Angular 7 from a JSON document

When it comes to displaying content in Angular 7 components, JSON is used. However, I have encountered a problem while trying to incorporate SVG icons from our UX team into the component using JSON. Using the img tag restricts me from applying a CSS class ...

There is no overload that fits this call (regarding a basic array retrieved from an api)

While attempting to utilize a .map function on a simple array (['a','b','c']) fetched using the useEffect hook, I encountered an error in TypeScript. The array elements rendered correctly when the code was executed and no erro ...

What scenarios call for utilizing "dangerouslySetInnerHTML" in my React code?

I am struggling to grasp the concept of when and why to use the term "dangerous," especially since many programmers incorporate it into their codes. I require clarification on the appropriate usage and still have difficulty understanding, as my exposure ha ...

Determine the category of a container based on the enclosed function

The goal is to determine the type of a wrapper based on the wrapped function, meaning to infer the return type from the parameter type. I encountered difficulties trying to achieve this using infer: function wrap<T extends ((...args: any[]) => any) ...

Executing a service request in Angular 2 using a versatile function

I have a function that determines which service to call and a function template for calling the service returned by that function. This function makes HTTP requests using http.get/http.post, which return an Observable and then perform a map operation on th ...

Tips for explaining the structure of a basic Just functor in TypeScript

I am embarking on my first attempt to create a simple interface in TypeScript, and I find myself questioning every step along the way. The core question that troubles me is: How can I best describe this straightforward Jest matcher extension? /** * @par ...

How to use ajax() to return multiple arrays successfully in jQuery

Hey everyone, I'm working on an AJAX function in jQuery that parses an XML file, creates an array on success, and wants to return multiple arrays on callback. Is it possible? If so, how can I achieve this? Please guide me through this. var arr1 = new ...

Detecting property changes in Angular 2: A step-by-step guide

I've created a basic class structure like so: export class MessagesPage { @ViewChild(Content) content: Content; public message = ''; public messages = []; public state = 'general'; } Can I implement a way wit ...