A guide on leveraging *ngFor in Angular 4 to assemble a table featuring 2 columns in every row

I have an array of objects as shown below

let columns = [
    {id: 1, columnName: 'Column 1'}, 
    {id: 2, columnName: 'Column 2'}, 
    {id: 3, columnName: 'Column 3'}, 
    {id: 4, columnName: 'Column 4'}
];

My goal is to use Angular's *ngFor directive to generate a table in the following format:

<table>
    <tr>
        <td>Column 1</td>
        <td>Column 2</td>
    </tr>
    <tr>
        <td>Column 3</td>
        <td>Column 4</td>
    </tr>
</table>

I aim to have two columns per row. I attempted to use *ngFor on <tr>, but couldn't achieve my desired outcome. Can you guide me on the correct approach to accomplish this?

Thank You :-)

Answer №1

If you want to achieve the desired structure in the view, one simple way is to modify the array's structure.

Here is a method to restructure the data:

tableData = columns.reduce((acc, col, i) => {
    if (i % 2 == 0) {
        acc.push({column1: col});
    } else {
        acc[acc.length - 1].column2 = col;
    }       
    return acc;
}, []);

Then, you can use the following code:

<table>
    <tr *ngFor="let row of tableData">
        <td>{{row.column1.columnName}}</td>
        <td>{{row.column2.columnName}}</td>
    </tr>
</table>

If you prefer not to alter the array, you could consider an alternative approach:

<table>
    <ng-container *ngFor="let col of columns; let i = index">
        <tr *ngIf="i % 2 == 0">
            <td>{{col.columnName}}</td>
            <td>{{i < columns.length - 1 ? columns[i + 1].columnName : ""}}</td>
        </tr>
    </ng-container>
</table>

Answer №2

In my opinion, converting your data into JSON format first would be beneficial. After that, you can easily implement the following code to achieve the desired output.

<table class='table' *ngIf="forecasts">
<thead>
    <tr>
        <th>Temp. (C)</th>
        <th>Temp. (F)</th>
    </tr>
</thead>
<tbody>
    <tr *ngFor="let forecast of forecasts">
        <td>{{ forecast.temperatureC }}</td>
        <td>{{ forecast.temperatureF }}</td>
    </tr>
</tbody>
</table>

Alternatively, you can also utilize the following code snippet with a different format:

<table>
<tbody *ngFor="let col of columns; let i = index">
    <tr *ngIf="i % 2 == 0">
        <td>{{col.columnName}}</td>
        <td>{{i < columns.length - 1 ? columns[i + 1].columnName : ""}}</td>
    </tr>
</tbody>
</table>

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

Meteor is failing to update the data in MongoDB

I have encountered an issue with the following code snippet: Nodes = new Meteor.Collection("nodes"); [...] Template.list.events({ 'click .toggle': function () { Session.set("selected_machine", this._id); Nodes.update(Session.get("s ...

Guide to assigning an integer value to a string in Angular

Is there a way to change integer values in a table to actual names and display them on a webpage by setting a scope in the controller and passing that string to the HTML? For example, this is an example of the HTML code for the table row: <thead> ...

The issue with launching a Node.js server in a production environment

I'm currently facing an issue when trying to start my TypeScript app after transpiling it to JavaScript. Here is my tsconfig: { "compilerOptions": { "module": "NodeNext", "moduleResolution": "NodeNext", "baseUrl": "src", "target": " ...

What is the appropriate utilization of the await keyword within concise if-else statements in JavaScript?

Along with transitioning away from jQuery, my main focus is to make my code more efficient. In large scale enterprise applications, the excessive use of jQuery and JavaScript can become problematic. I have decided to switch back to vanilla JavaScript for ...

Button functionality works smoothly on desktop but experiences issues with multiple submissions on mobile devices such as iPhones

Preventing multiple form submissions in asp.net webform functions correctly on a desktop version, but encounters issues on the mobile version of Safari or Chrome on iPhone. The following script prevents users from submitting the same form multiple times b ...

Collaborate on Typescript Interfaces within a Firebase development environment

I've been developing a Firebase project using Angular for the frontend, and incorporating the @angular/fire library. Within this project, I have created multiple interfaces that utilize firebase and firestore types. For example: export interface ...

What is the best way to trigger a modal to appear when dynamically generated items are clicked?

My objective is to retrieve specific data from the server and present it in a list format on my webpage. The list displays correctly, but I want users to be able to view additional details for each list item by clicking on it, triggering a modal popup. How ...

Angular 2: Enhancing User Experience with Pop-up Dialogs

Looking to implement a popup dialog that requests user input and returns the value. The popup component is included in the root component, positioned above the app's router outlet. Within the popup component, there is an open() method that toggles a ...

Issue with the svg animation not properly "executing"

Hello everyone! This is my debut post, and usually I can find solutions by browsing the community. However, this time I am in need of some assistance. I have crafted an "SVG" file that includes animations depicting the different cycles of a day over a 24-h ...

Using a comma as a parameter separator is not valid

Having trouble setting up a WhatsApp button with a custom message, I wrote a JavaScript script and called it using onclick. I've tried adjusting quotation marks but nothing seems to be working. This issue might seem minor, but as a beginner in coding ...

Entity Framework AJAX Delete Functionality Fails to Operate

I'm puzzled as to why this isn't working. Here's the code: View <input type="button" value="Delete" onclick="deletefunction(@item.PhotoId)"/> Controller [HttpPost] public ActionResult Delete(int photoid) { var imgDelete = db.Ph ...

Tips for displaying an alert in the upcoming event loop

I recently started learning VueJS and decided to create a practice game to strengthen my understanding of the framework. http://jsfiddle.net/mzref4o0/1/ Within this game, the attack method is crucial in determining the winner: attack: function(isSpecial ...

How can I adjust the font size of information retrieved from a JSON file using ng2-smart-table?

I recently tried using the following CSS code: :host /deep/ ng2-smart-table {font-size:22px;} However, despite implementing this code, I have not noticed any change in the font size. ...

Invoking a function of a Redux-form React component

Is there a way to access the component method of a redux-form? I want my upload button to submit the form and also open the file select dialog if the user hasn't selected any file. Here is my code: UploadModal.js import React from 'react&apos ...

Encountering a TypeError: relativeURL.replace is not a valid function in Next.js

Why am I encountering this error in my Next.js application? TypeError: relativeURL.replace is not a function. (In 'relativeURL.replace(/^/+/, '')', 'relativeURL.replace' is undefined) Request.js file const API_KEY = process ...

I am experiencing an issue where my code is not iterating over the data in my

The issue I'm facing with the code below is that it only displays the quantity of the first item, rather than all items in my shopping cart. import {ShoppingCartItem} from './shopping-cart-item'; export class ShoppingCart { constructor ...

Is it possible to enable password authentication on Firebase even if the user is currently using passwordless sign-on?

In my frontend JS project, I have integrated Firebase for web and am utilizing the passwordless (email link) authentication method for users. I am now interested in implementing password sign-on for an existing user who is currently using passwordless si ...

Setting the initial selection in an Angular 2 Select Component

My goal is to develop a select component wrapper in Angular 2 using ngModel. Although the events work correctly once the selection changes, I am facing an issue with setting the initial selection when it's first rendered. Here is the code for my comp ...

Just incorporated Angular Material and Angular Animations into my project and encountered a slew of errors

After executing the command line: npm install --save @angular/material @angular/animations This snippet shows my package.json file: { "name": "cerpnew", "version": "0.0.0", "license": "MIT" ...

Is there a way to monitor the home button press event within a PhoneGap application?

Hello! I'm curious if there is a way to track when the Home button is pressed on both Android and IOS using phonegap phonegap build. I have looked into events for the home button press, but have only found information on back button events so far. ...