Attempting to showcase an array by utilizing a *ngFor directive

I used lodash to group a data array and successfully viewed the output in my console. However, I'm encountering an issue where my *ngFor loops are not displaying the data on my HTML page. Can anyone help me figure out what I might be missing?

In my app.component.ts file:

export class AppComponent {
  name = "Angular";

  // Data array
  data = [
    {
      customer: {
        name: "John"
      },
      transaction_date: "2017-04-18"
    },
    {
      customer: {
        name: "Dick"
      },
      transaction_date: "2017-06-30"
    },
    {
      customer: {
        name: "Harry"
      },
      transaction_date: "2017-04-03"
    },
    {
      customer: {
        name: "John"
      },
      transaction_date: "2017-05-03"
    }
  ];

  constructor() {}

  ngOnInit() {
    // Sorting by Month
    
    // Formatting month
    const monthName = item =>
      moment(item.transaction_date, "YYYY-MM-DD").format("MMM");

    // Grouping by month
    const byMonth = _.chain(this.data)
      .groupBy(monthName)
      .mapValues(items => _.map(items, "customer.name"))
      .value();
    console.log(byMonth);
    return byMonth;

    // Sorting by Day 
    const dayName = item =>
      moment(item.transaction_date, "YYYY-MM-DD").format("DD");

    // Grouping by Day
    const byDay = _.chain(this.data)
      .groupBy(dayName)
      .mapValues(items => _.map(items, "customer.name"))
      .value();
    console.log(byDay);
    return byDay;
  }
}

In my app.component.html file:

<table *ngFor="let month of months">
    <tr>
        <th>{{month.month}}</th>
    </tr>
    <tr>
        <td>
            <table *ngFor="let customer of customers">
                <tr>
                    <td>
                        {{customer.name}}
                    </td>
                </tr>
            </table>
        </td>
    </tr>
</table>

Desired Format (within a table - formatting may not display):

  • April
    • John
    • Harry
  • May
    • Dick
  • June
    • John

Thank you for any assistance you can provide!

Answer №1

You're almost there, just a few things to correct.

1) Make sure to define a public property in your component that will be used for looping. I've created public myData as an example.

2) Next, initialize this object with the data you want to show. Instead of returning from ngOnInit, assign the data to your public property myData.

3) Remember that Angular ngFor cannot directly loop through non-array items by default. But since Angular 6, you can use the pipe | keyvalue to loop over objects.

Here is a link to a working demo on StackBlitz

Sample code snippet for better understanding...

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

Display all options in jQuery-UI Autocomplete when there are no matches found

Can jQuery Auto-complete display all available sources if the input does not match any of them? For example, in the code snippet below, how can I make it so that when typing "pineapple", all programming languages are displayed instead of none? <script ...

Hover effect for Twitter-like buttons

Can someone help me figure out how to create a link control similar to Twitter's functionality? I'm referring to the way that on a tweet page, when you hover over a tweet, links appear for reply, delete, and favorite, but disappear when not hove ...

Data retrieval issue with ng-table displaying information queried from HTTP request

I have been attempting to create an ng-table using ajax data with angularjs and rails. Despite successfully retrieving the data through an http get request, I am encountering difficulties appending it to my table as it always displays no records. Below is ...

AngularJS: engaging search experience

I'm just starting to learn AngularJS, and I have a project where I need to create an interactive search feature. So far, this is what I have: article/views/articles.html <form class="form-inline"> <div class="form-group"> < ...

Modifying the HTML <select> element with JavaScript

[resolved] I'm encountering an issue with the code below that is supposed to dynamically change the options in a second drop-down menu based on the selection made in the first menu. I've tried to troubleshoot the problem but haven't been suc ...

Discovering the functions of the Material 2 toolbar

I'm encountering an issue while trying to add a toolbar using material2 card. Here is my code snippet: <md-toolbar [color]="red"> <span>My Application Title</span> </md-toolbar> In my app.module.ts file, I have imported va ...

Developing play and pause capabilities using JavaScript for the existing audio player

Currently, I am developing a Chrome extension that includes an HTML popup with buttons to play audio files. However, I feel that my current approach is not the most efficient and I am struggling to find ways to simplify the process. The method I am using n ...

Steering clear of Unique error E11000 through efficient handling with Promise.all

In my development work, I have been utilizing a mongoose plugin for the common task of performing a findOrCreate operation. However, I recently discovered that running multiple asynchronous findOrCreate operations can easily result in an E11000 duplicate k ...

End the connection to mysql once several queries have been executed

I am currently working on a project that involves fetching data from an API using node.js and running multiple mysql queries in a loop to update rows. However, I am facing an issue where the script keeps running until I manually terminate the mysql connect ...

A step-by-step guide on extracting all documents within a directory collection from the official national archives website using the R programming language

I'm currently seeking a way to scrape all available files for a data file series on archive.gov programmatically using R. It seems that archives.gov utilizes JavaScript. My objective is to extract the URL of each available file along with its name. T ...

Dynamically change class on scroll using VueJs

Struggling to add and remove a class from the header on scroll without success. The class is currently being added multiple times with each scroll, resulting in duplication. How can I ensure the class is only added once and removed when ScrollY < 100? ...

Attempting to conditionally map an array of objects

I am currently working on conditionally rendering content on a screen. My main task involves manipulating an array of 3 objects with sub-objects, stored as the initial state in my reducer (using dummy data). The layout includes a customized SideNav bar wit ...

What are the steps to design a navigation bar inspired by the Angular Material 2 website?

In my quest to master the fusion of Material and Angular for applying the Material Design pattern to my applications, I stumbled upon Material2 for Angular. Embarking on this journey, I dove into exploring its components, starting with the navigation secti ...

Is there a way to combine the key typings of a fixed key with a Typescript Record or dictionary

Is there a way to enhance the existing Record (or a { [key:string]: string } interface) by incorporating fixed keys and their corresponding types? Imagine we have the following example: const additionalValues = { some: 'some', other: &a ...

Utilize a pipe to seamlessly transfer data from MSSQL to a Node.js application

I am currently utilizing node along with node-mssql version 6.0.1 for handling large amounts of data retrieval from the database and transmitting it to the frontend using streams. Although I have attempted to implement pipe and stream functionality as rec ...

Is there a way to implement a local gltf loader in three.js to display on a GitHub server within my repository?

Every time I run code on my VS app, it works perfectly fine. However, when I try running it on GitHub, it shows an error 404 and gets aborted. I came across some documentation regarding this issue, but I'm having trouble understanding it. Check out ...

What is the best way to merge two nested arrays of objects in JavaScript that share a common parent?

Hello everyone, I am facing an issue when trying to combine two nested parent arrays of objects. I want to merge only the children items that have the same group parent. Here is my scenario: I have two arrays var arr1 = [{group: "a", items: [&quo ...

The function myComponent.map does not exist

I am currently storing information that I am trying to pass to a component responsible for creating Tabs and TabPanel components (Material-UI) based on the provided data. Here is how the information is structured: let eventCard = [ { title: "T ...

Display all collections in Mongo DB except for a specific one

Is there a way in MongoDB to retrieve all documents except for one named Test? The current code retrieves all the documents. db.getCollectionNames().forEach(function(collection) { var result = db[collection]; if(result !== 'Test') { ...

Error Encountered in Reactjs: TypeError When Looping Through State Array to Render JSX Component

Currently in the process of constructing a gallery view showcasing cards that are populated with images fetched through an axios API call. The API call is made within a useEffect hook and the resulting object is then stored using useState. However, when ...