Separate every set of 6 elements into individual DIVs, with any remaining elements placed

I have an array containing a total of n items. My goal is to group every 6 items into separate div elements. However, if the array has 15 items, I struggle to group the last three remaining items.

Although the following code successfully groups every 6 elements, it does not handle the last 3 remaining items:

<ng-container *ngFor="let item of mockData; let i = index;">
          <div class="inner-wrap" *ngIf="(i+1) % 6 ==0">
            <p *ngIf="mockData[i-5]">{{ mockData[i-5] }}</p>
            <p *ngIf="mockData[i-4]">{{ mockData[i-4] }}</p>
            <p *ngIf="mockData[i-3]">{{ mockData[i-3] }}</p>
            <p *ngIf="mockData[i-2]">{{ mockData[i-2] }}</p>
            <p *ngIf="mockData[i-1]">{{ mockData[i-1] }}</p>
            <p>{{ item  }} </p>
          </div>
</ng-container>

Answer №1

To demonstrate the concept, we will create sub-arrays, iterate through them, and then loop through each sub-array to display it as a div element


To achieve this functionality in your .ts file, you can implement the following function:

createMockGroup() {
    return (mockData || [])
      .reduce((a, _, i, arr) => {
        if (i % 6 === 0)
          a.push(arr.slice(i, i + 6));
        return a;
      }, []);
}

In your .html file, make the necessary changes as shown below:

<ng-container *ngFor="let group of createMockGroup()">
    <div class="inner-wrap">
      <ng-container *ngFor="let item of group">
         <p>{{ item }} </p>
      </ng-container>
    </div>
</ng-container>

This approach eliminates the need to explicitly use the index variable

Answer №2

Make sure to also verify if there is any remaining items after grouping by 6. Below is an example of code snippet:

<ng-container *ngFor="let item of mockData; let i = index;">
          <div class="inner-wrap" *ngIf="(( (i+6) < mockData.length) && ((i+1) % 6 ==0)) || (i == mockData.length - (mockData.length % 6))">
            <p *ngIf="mockData[i-5]">{{ mockData[i-5] }}</p>
            <p *ngIf="mockData[i-4]">{{ mockData[i-4] }}</p>
            <p *ngIf="mockData[i-3]">{{ mockData[i-3] }}</p>
            <p *ngIf="mockData[i-2]">{{ mockData[i-2] }}</p>
            <p *ngIf="mockData[i-1]">{{ mockData[i-1] }}</p>
            <p>{{ item  }} </p>
          </div> 
</ng-container>

Answer №3

Looking at the code snippet provided:

<ng-container *ngFor="let item of mockData; let i = index;">
  <div class="inner-wrap" *ngIf="i % 6 ==0">
    <p>{{ item }} </p>
    <p *ngIf="mockData[i+1]">{{ mockData[i+1] }}</p>
    <p *ngIf="mockData[i+2]">{{ mockData[i+2] }}</p>
    <p *ngIf="mockData[i+3]">{{ mockData[i+3] }}</p>
    <p *ngIf="mockData[i+4]">{{ mockData[i+4] }}</p>
    <p *ngIf="mockData[i+5]">{{ mockData[i+5] }}</p>
  </div>
</ng-container>

Check out the live example here

Answer №4

<ng-container *ngFor="let groupIndex of createGroupData(mockData, 6);">
    <div class="wrap-inner">
        <p *ngIf="mockData[(groupIndex*6)]">{{ mockData[(groupIndex*6)] }}</p>
        <p *ngIf="mockData[(groupIndex*6)+1]">{{ mockData[(groupIndex*6)+1] }}</p>
        <p *ngIf="mockData[(groupIndex*6)+2]">{{ mockData[(groupIndex*6)+2] }}</p>
        <p *ngIf="mockData[(groupIndex*6)+3]">{{ mockData[(groupIndex*6)+3] }}</p>
        <p *ngIf="mockData[(groupIndex*6)+4]">{{ mockData[(groupIndex*6)+4] }}</p>
        <p *ngIf="mockData[(groupIndex*6)+5]">{{ mockData[(groupIndex*6)+5] }}</p>
    </div>
</ng-container>

add this function to your component:

createGroupData(array, num){
    let groups = [];
    let maxNumber = (array.length % num) == 0 ? (array.length / num) : (array.length / num)+1;

    for(var i = 0; i < maxNumber; i++) {
        groups.push(i);
    }
    return groups;
}

Answer №5

within your component

@Pipe({
    name: 'filter'
})
@Injectable()
export class FilterPipe implements PipeTransform {
    transform(items: any[]): any[] {
     const result = [];
     for (var i = 0; i < items.length; i += 6) {
      result.push(items.slice(i, i + 6));
     }
     return result;
    }
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  number = ['', ' ', '', '', '', '', '', '' ];

}

and in the html

<div *ngFor="let item of number | filter ; let i = index" style="border: 1px solid;margin-bottom:20px">
<div *ngFor="let element of item; let j = index" style="">
  element {{i}} , {{j}}
</div>
</div>

Try it out on StackBlitz - https://stackblitz.com/edit/angular-ppnxnm

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

Spread an all-encompassing category across a collection

What is the method in TypeScript to "spread" a generic type across a union? type Box<T> = { content: T }; type Boxes<string | number> = Box<string> | Box<number>; (Given that we are aware of when to use Boxes versus Box) ...

Unable to associate with 'userID' as it is not a recognizable attribute of 'view-user'

When looking at my template expression, I came across the following: This points to the ViewUserComponent, which includes: @Input() userID; I'm puzzled as to why I'm encountering this error: Can't bind to 'userID' since it isn& ...

Any tips on how to personalize the loading animation for single pages using CSS and GIFs?

presentLoading(message) { this.loading = this.loadingCtrl.create({ dismissOnPageChange: false, spinner:'hide', content:`<img class="load" src="assets/dual.gif" />`, }); this.loading.present(); } Hello there! I am working with the ...

Issue encountered: Nuxt 3 fails to locate the useRoute import

Recently, I updated to the latest version of Nuxt and encountered an issue with the useRoute method. Even though it works, I keep getting a "Cannot Find name useRoute" error message. Can anyone help me figure out what might be missing? <script lang=&quo ...

What is the reason for the inconsistency between Angular locale definition files and the corresponding locale identifiers used for registerLocaleData?

I've been attempting to dynamically load locale data from the Angular framework using locale identifiers and call RegisterLocaleData, but I've encountered issues due to framework naming conventions. Here is a function that I wrote: public import ...

Premature updates detected in state cloning process

My program is a simple one designed to showcase an issue I am currently encountering. It involves an array of objects, each containing a sequence number. When a button is clicked, the sequence number of the first object in the array increases by one. To i ...

Restrain a Key according to the data type of its value within a universal category

I am currently working on creating a versatile function where the generic type is used to define its parameter. Here's an excerpt from this parameter : type Configuration<T> = { masterdata: T[], target: ???? } I am encountering difficu ...

Using type definitions in non-TS files with VSCode: A beginner's guide

My code is not in TypeScript, shown here: // foo.js module.exports = app => { // some logic here } I want to enhance my development experience by using TypeScript definition files to specify the type of the argument app, enabling VSCode to provide ...

"ng-new" is not currently present in the "@schematics/angular" collection

After removing npm and node, as well as homebrew, I restored them by downloading from the online site. I also installed the Angular cli using npm. Navigating to my desktop in the terminal, I entered: ng new mag-board to initiate my angular project. Howev ...

Exploring the proper way to infer generic types for Redux Toolkit Slices

I've been working on a function that takes a slice factory as an argument and performs some operations on it. However, I'm facing challenges in setting up the types correctly. Below is a simple example showcasing the issue: Slice factory: expor ...

Unable to display the attributes of an object using console.log

I am attempting to log the properties of an object in TypeScript, but I am encountering issues. setTitleAndBody(result: { title: String; body: String; }) { console.log(result) console.log(result.title) } What's interesting is that if I only l ...

Is there a way to accurately identify the type of error that arises from a promise?

Utilizing the promise method within my script is essential. try { const secretData = await secretManager.getSecretValue({ SecretId: secretId }).promise(); const secretString = secretData.SecretString; } catch (error) { if (error.code !== &a ...

What is the reason for TypeScript's prioritization of arguments over assignment in generic inference?

When it comes to Typescript generics inference, the priority is given to arguments over assignment. This means that any param props are automatically converted into type unknown, even if they are assigned to a variable whose type param is set to an object ...

Troubleshooting typescript error in styled-components related to Material-UI component

When using typescript and trying to style Material UI components with styled-components, encountering a type error with StyledComponent displaying Type '{ children: string; }' is missing the following properties import React, { PureComponent } f ...

Dayjs is failing to retrieve the current system time

Hey everyone, I'm facing an issue with using Dayjs() and format to retrieve the current time in a specific format while running my Cypress tests. Despite using the correct code, I keep getting an old timestamp as the output: const presentDateTime = da ...

Is it better for a data service's observable to emit a sequence of objects or an array of objects?

Currently diving into the world of Angular and RxJS, I find myself puzzled about the preferred return type for a data service. Should it be a sequence of objects or an array of objects? What's considered best practice? import { from, of } from &apos ...

Executing a TypeScript function through a package.json script: A guide

I'm currently using a javascript function from my package.json script, but I want to switch it to a typescript function in a typescript file. Can someone advise me on how to make this adjustment? This is the javascript code that runs the desired func ...

Issues with Angular polyfills core-js causing unexpected behavior in IE11

I'm encountering challenges when trying to display my Angular application in IE 11 I've referred to the guidelines provided here: In addition, I have imported the following polyfills: import 'core-js/es/symbol'; import 'core-js ...

What is the best way to automatically close a sidebar in Angular 8 depending on the window size when the page loads?

Is there a way to ensure that the sidebar remains closed when loading the page on a window with a width of less than 850 pixels? I have attempted implementing the following code, however it only functions properly when I manually resize the window: @ ...

What is the best way to set up the user's editable information in the input field?

Is it possible for a user to edit their data? I have made the data accessible on this page, stored in information. I would like the user to see their data upon entering the view, such as their username or email, and be able to edit or delete it. I initiall ...