Exploring table iteration in Angular 7

I am looking to create a table with one property per cell, but I want each row to contain 4 cells before moving on to the next row...

This is what I want:

<table>
      <tr>
        <td>
          <mat-checkbox>1</mat-checkbox>
        </td>
        <td>
          <mat-checkbox>2</mat-checkbox>
        </td>
        <td>
          <mat-checkbox>3</mat-checkbox>
        </td>
        <td>
          <mat-checkbox>4</mat-checkbox>
        </td>
      </tr>
      <tr>
        <td>
          <mat-checkbox>5</mat-checkbox>
        </td>
        <td>
          <mat-checkbox>6</mat-checkbox>
        </td>
        <td>
          <mat-checkbox>7</mat-checkbox>
        </td>
      </tr>
    </table>

I attempted the following code, but all values appear in a single column:

lista = [
    { value: "1" },
    { value: "2" },
    { value: "3" },
    { value: "4" },
    { value: "5" },
    { value: "6" },
    { value: "7" },
<table *ngFor="let list of lista">
   <tr>
     <td>
       <mat-checkbox>{{ list.value }}</mat-checkbox>
     </td>
   </tr>
</table>

Answer №1

To start, organize your array into groups of 4 (chunk size), then proceed to loop through it in your template.

Within your component:

const data = [
    { value: "1" },
    { value: "2" },
    { value: "3" },
    { value: "4" },
    { value: "5" },
    { value: "6" },
    { value: "7" }
];

const chunkSize = 4;

// Divide the data into chunks of 4 and filter out any falsy values
const groups = data
.map((item, index) => { 
     return index % chunkSize === 0 ? data.slice(index, index + chunkSize): null; 
})
.filter(item => item);

Incorporate the following structure into your template:

<table >
   <tr *ngFor="let items of groups">
     <td *ngFor = "let innerItems of items">
       <mat-checkbox>{{ innerItems.value }}</mat-checkbox>
     </td>
   </tr>
</table>

Answer №2

If you want to create a table using a 2d array, you can follow this structure:

  data = [
[
  {value: '1'},
  {value: '2'},
  {value: '3'},
  {value: '4'}
],

[
  {value: '5'},
  {value: '6'},
  {value: '7'},
  {value: '8'}
]
 ];

When it comes to displaying it in HTML, you can use the following code:

<table >
  <tr *ngFor="let row of data">
    <td *ngFor="let col of row">
      <mat-checkbox>{{ col.value }}</mat-checkbox>
    </td>
  </tr>
</table> 

Answer №3

To create a table layout where each row contains four elements, you can adjust the iteration logic in your Angular template. Check out the revised code below:

<table>
  <tr *ngFor="let item of items; let i = index">
    <ng-container *ngIf="i % 4 === 0">
      </tr><tr>
    </ng-container>
    <td>
      <mat-checkbox>{{ item.value }}</mat-checkbox>
    </td>
  </tr>
</table>

In this updated snippet, a new row is opened and closed every four iterations within the loop. This ensures that each row consists of exactly four checkboxes.

The condition i % 4 === 0 determines when to start a fresh row by checking if the current index (i) is divisible by 4. If true, the closing and opening tags are applied accordingly.

Adopting this method guarantees that the items will be organized into rows with four checkboxes per row until all items have been processed.

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

The fix for the unresponsive fixed container in Angular 2 Material

I've encountered an issue with CSS and Angular 2 material. Any element with a fixed position doesn't behave as expected inside an md-sidenav-container. However, when it is placed outside the container, it works perfectly. I have created a Plunker ...

The measurement of a HTML window's entire content height (not just the visible viewport height)

Currently, I am attempting to determine the total height of a webpage's content, not just what is visible. In my efforts, I have managed to achieve some success in FireFox using: document.getElementsByTagName('html')[0].offsetHeight. Howeve ...

Display the initial x list items without utilizing ngFor in Angular 2

In the template, there are 9 <li> elements, each with a *ngIf condition present. It is possible that 5 or more of them may return true, but the requirement is to only display the first 4 or less if needed. Priority is given to the order of the < ...

Content within a Row of a Data Table

Hello! I am just starting to learn JavaScript and jQuery. Can you help me with an issue I am experiencing? Basically, I have a table and I need to identify which tr contains a td with the text "Weekly", "Daily", or "Monthly". Once I locate that specific t ...

Issues with type errors in authentication wrapper for getServerSideProps

While working on implementing an auth wrapper for getServerSideProps in Next.js, I encountered some type errors within the hook and on the pages that require it. Below is the code for the wrapper along with the TypeScript error messages. It's importan ...

ASP.NET CodeBehind Fails to Recognize Changes in TinyMCE Textarea

I have multiple <asp:TextBox TextMode="MultiLine"> elements on a webpage. Initially, I populate them using VB code behind and then convert them into TinyMCE editors with the help of the jQuery TinyMCE plugin. Each text box has an associated button fo ...

Drop-down options disappear upon refreshing the page

Code snippet for sending value to server using AJAX in JavaScript In my script, the status value may vary for each vulnerable name. When selecting a status option and storing it in the database through AJAX, the selected value is lost after refreshing th ...

Customize the border color of a dynamic textbox with Angular

I'm using Angular to create dynamic textboxes. <span *ngFor="let list of lists[0].question; let i = index"> {{ list }} <input type="text" *ngIf="i != lists[0].question.length-1" [(ngModel)] ...

Tips for importing the mongoose-long plugin using the ES6 method

How can I rewrite the given import syntax into ES6 import format? import mongoose from 'mongoose'; import 'mongoose-long'(mongoose); import { Types: { Long } } from mongoose; ...

"Exploring the World of Angular and Vue: Harnessing the Power

As a beginner developer, I've been busy familiarizing myself with Angular, React, and Vue. It seems like each of these frameworks use "declarative binding" and "templating". While I grasp the concept of what these are, I'm struggling to see why t ...

Turn off the scroll function while loading a webpage

Here is the script for my preloader: $(window).load(function() { $("#loading").fadeOut(1000); I want to prevent scrolling while the "loading" is still visible, and then enable it again after the fade out completes. ...

Encountering an issue when attempting to save JSON data in the database: unable to convert object into a string

To summarize, my data is stored in Javascript: JSONdata = { name: form.name.value, address1: form.custa.value, address2: form.custa2.value, postcode: form.custpc.value, order: fullorder, cost: document.getElementById('total&ap ...

JavaScript's replace() method and the $1 issue

My goal is to develop a script that can identify specific patterns within text and then enclose them in particular tags upon identification. $(".shop_attributes td").each(function () { $(this).html(function(i, html) { return html.replace(/E[0- ...

Utilizing Protractor's advanced filtering techniques to pinpoint the desired row

I am trying to filter out the specific row that contains particular text within its cells. This is my existing code: private selectTargetLicense(licenseName: string) { return new Promise((resolve => { element.all(by.tagName('clr-dg-tab ...

Enhance the structure of information retrieved from the API

Recently I sought advice on formatting API data and received some excellent responses. However, I encountered an error when the API lacked data for certain assets: https://i.stack.imgur.com/HgJDd.png Here is an example without the highlighted code: http ...

What steps can I take to ensure that the elements are in the same row instead of being displayed in three separate rows?

(I'm a beginner in web development and need some help) Is there a way to align elements into the same row instead of stacking them up in separate rows? I'm working on creating a header bar similar to the one on the Naive UI Documentation Website. ...

The JavaScript exec() RegExp method retrieves a single item

Possible Duplicate: Question about regex exec returning only the first match "x1y2z3".replace(/[0-9]/g,"a") This code snippet returns "xayaza" as expected. /[0-9]/g.exec("x1y2z3") However, it only returns an array containing one item: ["1"]. S ...

Dynamic rendering of independent routes is achieved by nesting a router-outlet within another router-outlet

I am working on an angular 2 project with multiple modules. To load each module, I am using the lazy loading technique in this way: { path: 'home', loadChildren: './dashboard/dashboard.module#DashboardModule' }, Currently, I am facing ...

Customizing the header template in ag-Grid for Angular 2

I have implemented ag-grid within an ng2 component. Now, I am trying to make the first header a checkbox with the parent functionality. How can I achieve this from the container component? ag-grid.component @Component({ moduleId: module.id, selecto ...

Creating a Custom Form Control in Angular 2 and Implementing Disable Feature

I have developed a unique custom control using ControlValueAccessor that combines an input[type=text] with a datepicker. While the template-driven forms accept it without any issues, the situation changes when implementing the model-driven approach (react ...