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

Insert a new row with a designated row class

I have a table with 2 columns and an "add row" button. However, I want to add a new row between the rows with the classes "title" and "ongkir". Currently, the new row is being added after the "ongkir" row. Can someone please assist me in achieving this? B ...

Toggle the row to expand or collapse upon clicking it

After extensive research, I have been unable to get the row expansion and collapse feature to work in my script. Here is my current script: <thead> <tr> <th width="5" class="cb"><input type="checkbox" id="cbcall" /& ...

What caused the mat-date calendar style to malfunction?

I integrated mat-date into my Angular project, but encountered an issue where the styles of the calendar were not displaying properly when clicking the icon. Here is the displayed calendar effect I attempted to troubleshoot by commenting out the styles o ...

Dynamically pass a template to a child component

How can I dynamically load content on my page based on the active navigation point? export class Sub_navigation_item { constructor( public title: string, public templateName: string ) {} } I have a navigation item with an ID from an ...

What is the method for making an interface extension from a type as optional?

Can you help me create an interface that includes all students and part of a school, ensuring that gender is required for Peter and optional for other students? export type School = { address: string; state: string; }; export type Gender = { gender: ...

What is the process for assigning the value returned from an Angular HTTP request to ng-bind?

I am trying to retrieve a value from an HTTP request in AngularJS and set it as the result in a variable that is bound to ng-bind. The goal is for the value returned from the HTTP request to be displayed when text is typed into an input field. Below is th ...

I am looking to create a unique JavaScript variable within my GTM container that will automatically return a value of true when the user approves sharing

Is there a way to trigger a tag when the user shares their location with the browser? I attempted using the following code within a custom JavaScript variable in my GTM Container, but it didn't seem to work. navigator.permissions && navigator ...

Sort values depending on the value of another key

I have a list of different types: const types = ['BAKERY', 'FRUITS', 'RESTAURANT', ...]; The length of this array is not fixed. Additionally, I also have a corresponding category list for each type as shown below: const categ ...

Implementing bi-directional data binding between sibling components in Vue.js

Is it possible to create a dual binding scenario with the typeahead plugin https://github.com/pespantelis/vue-typeahead, where the search terms of two typeaheads are linked? This means that regardless of which search box the user types into, both should ...

Having trouble modifying the fields in the formArray

Working with reactive forms, I have a UI feature that displays radioButton options which, when selected, reveals details about the chosen value within the form. Once a button is selected, the form fetches data from the backend. The structure of my form is ...

Remove an image that has been selected while uploading multiple images using AngularJS

If I want to delete a specific image from multiple uploads by clicking on the image in AngularJS, how can I achieve this? Each uploaded image has an associated textbox. When the delete icon on the image is clicked, both the image and the corresponding text ...

Incorporate an HTTP Header into a Wicket Ajax Request

I am trying to include a custom HTTP header in all Ajax (XHR) requests made by Wicket. I attempted the following: $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('X-My-Header', 'value'); } }); and $(doc ...

What is the process for obtaining intersection set data from an array?

I'm trying to find the intersection set within an array only containing type 1 and 2. Can you help me with that? var arr = [ { id: 1, auths: [ { authId: 1, type: 1, value: 'Test1' }, { authId: 2, type: 1, ...

The field 'name' is not recognized on type 'never'

Currently immersing myself in Angular and experimenting with making an API call, but I'm encountering the following error: error TS2339: Property 'name' does not exist on type 'never'. import { Component, OnInit } from '@angu ...

Step-by-step tutorial on how to enable app logout functionality using Node.js and Okta

I have created a web app using Okta with OIDC and Node Express for user authentication. I want users to be able to log out of my app without logging out of the company Okta, which is used for multiple websites. Okta recommends this approach on their websit ...

creating infowindows on the fly for numerous markers

I'm struggling to populate Google InfoWindows with dynamic content. My current approach involves loading 60 markers and attaching a click event handler to each one. Upon clicking a marker, I aim to retrieve the corresponding data from a fusion table b ...

Creating a dynamic slider using jQuery

Here is the code snippet I have been working on: var current_slide = 1, animation_time = 1000, pause = 3000, slide_container = $('.slide_container'), interval, height = slide_container.height(), slides ...

Holding an element in TypeScript Angular2 proved to be challenging due to an error encountered during the process

I attempted to access a div element in my HTML using ElementRef, document, and $('#ID') but unfortunately, it did not work. I tried implementing this in ngOnInit, ngAfterViewInit, and even in my constructor. Another method I tried was using @Vie ...

The error message "Property is not found on type 'Object'" suggests that the property being accessed does not

I wrote a function called getAll getAll<T>() { return this.http.get(`${environment.apiUrl}/products`); } Here is how I am invoking it: this.productService.getAll() .pipe(first()) .subscribe(products => { debugger let s ...

Utilizing JSON and CodeIgniter within HTML elements

I am interested in creating a private chatroom using CodeIgniter and JSON format. I want the JSON data retrieved to be displayed in a list structure like <ul><li>messageinJSON</li></ul>. This formatting will allow me to customize th ...