Looping through an array of objects with Angular 4's ngFor directive to dynamically display content

I am working with Angular 4 and I am attempting to iterate through an array of objects to present the data in Angular Material grid tiles. The code snippet from my HTML file (app.component.html) is as follows:

<div class="list" *ngIf="listContacts == true">
 <mat-grid-list cols="3" rowHeight="2:1" *ngFor="let contact of contacts">
  <mat-grid-tile>
    <div class="card">
      <img src="{{contact.image}}" alt="picture">
      <h2>{{contact.name}}</h2>
    </div>
  </mat-grid-tile>
 </mat-grid-list>
</div>

The 'contacts' variable is an array of objects in the app.component.ts file. Within this array, there are currently nine objects, but for simplicity's sake, I have only displayed two here.

export class AppComponent {
// Array of contact objects
contacts = [
{
  name: "Robbie Peck",
  image: "src/assets/robbie.jpg",
}, 
{
  name: "Jenny Sweets",
  image: "src/assets/jenny.jpg",
}, 

...

]
}

Instead of rendering nine separate tiles, each containing unique information (iterating through 'contacts' with the 'contact' variable), only one tile is being displayed. Furthermore, the console is showing an error related to the 'contacts[i]' notation. What mistake have I made? How can I ensure that the grid displays 9 tiles, each with the respective 'name' and 'image' properties found in the 'contacts' object in the corresponding typescript (app.component.ts) file?

Answer №1

To access the image and name of each element in the contacts array, you can simply use the variable i and refer to i.image and i.name

<mat-grid-list cols="3" rowHeight="2:1" *ngFor="let i of contacts" >
 <mat-grid-tile>
    <div class="card">
      <img src={{i.image}} alt="picture">
      <h2>{{i.name}}</h2>
    </div>
  </mat-grid-tile>

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

Discovering the best way to organize and sort information retrieved from the backend within an Angular

How can I restrict a user to only search for data that has been provided from the backend and prevent them from creating new data? In my backend, there are two words: "Chart" and "Map". I am looking for a way to limit the user's search to only these ...

Fetching DataItem from a Kendo Grid using a custom button in an Angular application

I have been working on transferring the dataItem from a Kendo grid to an Angular 6 component. Here is my setup: <kendo-grid [data]="view | async" [height]="533" (dataStateChange)="onStateChange($event)" (edit)="editHandler($even ...

It is not possible to use an async function with Ionic 4 ToastController buttons

Incorporating a new function into the handler of my ToastController button to return a promise (in this case: this.navCtrl.navigateForward()) is something I need assistance with. This is what my code looks like: const toast = await this.toastController.c ...

How can one retrieve a file in Silverlight without using Webclient?

I'm faced with a challenging task of downloading one file into a ByteArray, editing the ByteArray, simultaneously downloading another large file, merging the first edited file into it on-the-fly, and playing it using MediaElement. Although I can down ...

Angular 2 error: Unhandled Promise rejection stating that the template has parsing errors - the element 'login' is not recognized

I am currently attempting to implement Firebase Authentication login for an Angular2 project. However, I encountered the following error: Unhandled Promise rejection: Template parse errors: 'login' is not a known element: 1. If 'login&apos ...

Can components be SSGed individually rather than entire pages?

I am currently working with Next.js and I am wondering if there is a way to statically generate and display the database values in the header and footer components used across all pages. While getStaticProps can generate pages statically, it doesn't ...

Customize the columns of your Angular Material 2 table by defining them using TemplateRef and ngTemplateOutlet

Looking to create a flexible material table with the ability to utilize TemplateRef along with ngTemplateOutlet for generating columns. Check out this demo where I have employed the cards component within my custom material-table component. Inside the card ...

Tips for identifying and handling errors in Playwright

I'm going crazy trying to handle a TimeoutError that I know is coming. Currently, I'm testing the Hidden Layers scenario from UI Testing Playground in Playwright Node.js and I want to see if there's a way to prevent the TimeoutError from cau ...

PHP populate missing array indexes

I have an array that stores values per year and per week, retrieved from my database. The stored data may resemble the following: Array ( [2018] => Array ( [40] => 1 [41] => 1 [47] => 1 ...

Troubleshooting Cross-Origin Resource Sharing Problems when Accessing a Web Application from a Browser Outside an Azure Virtual Machine

Hello everyone, I currently have an Angular and Asp.net Core Application deployed on IIS within an Azure Virtual Machine. The application functions perfectly when accessed through the IIS Localhost on the Azure Virtual Machine. However, when attempting to ...

Enhance the efficiency of traversing a lengthy list of comparisons within an array.filter method

I am struggling with finding an efficient method to filter out items from an array of objects based on two specific attributes matching those of the last 6 items of another array. Currently, I have a manual process in place which results in cumbersome and ...

The duration of recorded audio in JavaScript is unclear

I managed to successfully create a structure for recording and downloading audio files. However, I'm facing an issue where the final downloaded file has an unknown duration. Is there any way to solve this problem?? Here is my Typescript code snippet: ...

The npm audit command flagged an issue with an invalid tag name,

Whenever I run npm audit on a directory containing the project's package.json and package-lock.json, I encounter the following error message: 0 info it worked if it ends with ok 1 verbose cli [ '/home/user/Downloads/node-v10.14.0-linux-x64/bin/n ...

The reason behind the ghost problem - classRef isn't recognized as a constructor

Recently, I encountered an issue where the app was not loading in the browser while running an Angular NX project locally with the command "start-dev": "nx run-many --target=serve --all". The screen would get stuck on our loading animat ...

Encountered an error stating 'name' property is undefined while using @input in Angular 2

Everything seems to be set up correctly, but I'm encountering an error in the browser console that says "Cannot read property 'name' of undefined": https://i.sstatic.net/TvfEr.png This is how my media.component.ts file is structured: impo ...

Filtering in JavaScript can be efficiently done by checking for multiple values and only including them if they are not

In my current coding challenge, I am attempting to create a filter that considers multiple values and only acts on them if they are not empty. Take the following example: jobsTracked = [ { "company": "Company1", ...

Stop the inheritance of static components in a feature module by protecting the router-outlet

I am in the process of dividing my app into multiple feature modules. Currently, I am using only the router-outlet inside a component within a feature module. However, this approach brings along all the static components such as the navbar and footer. How ...

Tips for inserting an HTML element within an exported constant

I need help formatting an email hyperlink within a big block of text. Here is the code snippet: const myEmail = '<a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e4b564f435e424b6e4b564f435e424b004d41 ...

Splitting an array into two equal halves in Swift: A step-by-step guide

I have a single array that I want to split into two separate arrays; the first containing the first half of the elements and the second containing the second half. Here is my attempted code: let totalArray = [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10] v ...

What steps can be taken to identify the two highest numbers in an array, one being positive and the other

Seeking the optimal solution to resolve this issue Issue: Develop a function called ArrayChallenge (Javascript) that takes a single argument "arr" representing an array of numbers. The function should return the string true if there exist two numbers in t ...