What is the best way to transform a for loop using array.slice into a for-of loop or map function in order to generate columns and rows

Experiencing an issue with Angular8. Seeking help to convert a for loop for an array into a loop utilizing either for-of or array.map.

The code in question involves passing an array of objects and the need to separate it into col and row arrays for visualization.


    private pages = [];
    public grid = [];
    public col = 2;
    public row = 2;
    public indexPage = 0;
    private gridSize = this.col * this.row;
    private items = [
        {
          url:'http://url1',
          name:'1',
          active: false,
        },
        {
          url:'http://url2',
          name:'2',
          active: false,
        },
        ...
      ]
ngOnInit() {
    if(this.col === 0 || this.row === 0) {
      this.grid = this.items;
    }else {
      for (let i = 0; i < this.items.length; i+= this.gridSize) {
         let page = this.items.slice(i , i+this.gridSize);
         this.pages.push(page);
      }
      for (let i = 0; i < this.pages.length; i++) {
        let pageUrl = [];
        for(let j = 0; j < this.pages[i].length; j+=this.col) {
          let urls = this.pages[i].slice(j , j+this.col);
          pageUrl.push(urls);
        }
        this.grid.push(pageUrl);
      }
    }
  }

Output from object with col = 2; row = 2:

pages --> (2) [Array(4), Array(3)]             
              --> (0) [{...},{...},{...},{...}] 
              --> (1) [{...},{...},{...}]       

grid --> (2) [Array(2), Array(2)]
            -->(0) [Array(2), Array(2)]   
                   --> (0)[{...},]{...}]    
                   --> (1)[{...},]{...}]    
           --> (1) [Array(2),Array(1)]   
                   --> (0)[{...},{...}]     
                   --> (1)[{...}] .        

Although output is accurate, there's a tslint error on the for loop:

Expected a 'for-of' loop instead of a 'for' loop with this simple iteration

Note: The rows and columns are customizable

Answer №1

Here is a way to transform your regular loops into for-of loops:

    const elements = [];
    let counter = 0;
    const limit = 10;

    while (counter < limit) {
        elements.push(counter);
        counter++;
    }

    for (const element of elements) {
        console.log(element);
    }

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

VSCode displaying HTML errors within a .ts file

There is a strange issue with some of my .ts files showing errors that are typically found in HTML files. For example, I am seeing "Can't bind to 'ngClass' since it isn't a known property of 'div'" appearing over an import in ...

having trouble retrieving 200 status code from Angular server response

Objective: I need to make certain changes to the record locally if the server responds with a 200 code. Problem: I am unable to retrieve the response code or access the 'message' attribute. This is the server response I receive from the HTTP ca ...

Compilation error occurred when running Angular with mat-form: ngcc encountered an issue while processing [email protected]

Currently dealing with a compile error in a small mat-form example that I created. Unfortunately, I am unable to pinpoint the exact issue causing this error. If you have a moment, please take a look at the code here: https://stackblitz.com/edit/angular-iv ...

Choose from the Angular enum options

I am working with an enum called LogLevel that looks like this: export enum LogLevel { DEBUG = 'DEBUG', INFO = 'INFO', WARNING = 'WARNING', ERROR = 'ERROR' } My goal is to create a dropdown select el ...

"Continue to shine until the rendering function displays its source code

I've encountered a strange issue where I'm using lit until to wait for a promise to return the template, but instead of the desired output, the until's function code is being rendered. For example: render() { return html` <div c ...

Ways to grant access beyond the local host

I am having trouble accessing my Angular2 application outside of localhost. I can easily navigate to localhost:3030/panel, but when I try to use my IP address like 10.123.14.12:3030/panel/, it does not work. Can someone please help me fix this issue? I am ...

Handling HTTP Client Errors in Angular 4.x

I am currently working on developing an application that utilizes Angular for the front end and Laravel 5.0 for the back end. One of the challenges I am facing is handling errors in HTTP requests. Here is an example from my MenuController.php, where I pr ...

Running the npm install command will eliminate any external JS or CSS files that are being

For my project, I incorporated jquery-datatimepicker by including jquery.datetimepicker.min.css and jquery.datetimepicker.full.min.js in angular.json and placed them within the node_modules/datetimepick directory. Here is a snippet of my angular.json conf ...

ArrangementGrid utilizing ngFor directive for rows and columns

Hi there, I am new to using Nativescript and I have encountered an issue with ngFor. Specifically, I am working with a GridLayout that contains a StackLayout inside of it and I need to set dynamic col and row values within the StackLayout. Can anyone pro ...

What is the best way to send information using an array of objects?

In my Angular 5 project, I am using the ngx select dropdown package (https://www.npmjs.com/package/ngx-select-dropdown) and I'm wondering how to pass an array of objects instead of an array of strings. Currently, when I do so, it displays [Object Obje ...

IE11 triggers DatePicker to display as NaN when changing the year

When attempting to manually adjust the year value in the input field rather than utilizing the popup, the datepicker switches the value to "NaN/NaN/NaN". This issue appears to be specific to IE11 as it works correctly in Chrome. ...

Is it possible to modify the HTML/CSS of a child component using the parent component in Angular 2+?

Is there a way to dynamically add text and style to a specific row in a child component based on the parent's logic? (parent): <body> <child-component></child-component> </body> (child): <div *ngfor = "let record in r ...

Checking if a string is present in an array object with Angular.js using a filter function

In my Angular and Firebase app, users can create new discussion topics and vote on existing ones. When a user is logged in, their username is stored in currentUser.username. If they've upvoted a topic, their username will also be added to the array of ...

What is the most effective method for comparing and updating objects within arrays or lists in frontend Angular applications using TypeScript?

While I acknowledge that this approach may be effective, I am of the opinion that there exists a superior method to accomplish the same goal I have two separate lists/arrays containing distinct objects, each with a common attribute. My objective is to ite ...

Decorate the elements that do not contain a specific child class

I'm currently working on an angular project with primeng for the UI components. My focus at the moment is on customizing the p-menu component, specifically the appearance of list items that are not active. The challenge I'm facing is that the act ...

Make the angular component refresh when the back button is pressed

I am working on a TeamSeasonComponent with the URL http://localhost:4200/teams/season/<team_id>. On this page, there are links to other team's pages which would take me to http://localhost:4200/teams/season/team_2_id>. I switch between these ...

Issue reported: "Usage of variable 'someVar' before assignment" ; however, it is being properly assigned before usage

This piece of code showcases the issue: let someVar: number; const someFunc = async () => { someVar = 1; } await someFunc(); if (someVar == 1) { console.log('It is 1'); } As a result, you will encounter ...

Angular 7 and Express: No content returned in response body after making a POST request

I am encountering an issue with retrieving the response from a POST request in Angular 7. When I set the API to return "text," everything works as expected. However, when I change the response to JSON, the response body in Angular appears to be null. Test ...

Update the input value with the selected option from the dropdown menu in Angular

How can I dynamically set the value of an input field based on the selection from a dropdown menu in Angular using Reactive Forms? Below is my HTML code: <nb-card> <nb-card-header> Services </nb-card-header> <nb-card-body&g ...

Angular downgrades from version 13.3.8 to 13.3.7

When I input the command: ng v I am shown the version as "Angular: 13.3.8" in the image. Can someone explain where this version is coming from and how can I change it back to 13.3.7? Furthermore, I noticed that the packages listed in the screenshot are d ...