Angular: Indexed Array not binding properly

I have decided to utilize the following data structure:

let availabilities = [
  "2019-7-15" : {id: 1, ...},
  "2019-7-16" : {id: 2, ...},
  "2019-7-20" : {id: 3, ...}
]

However, when trying to bind it in the template, it doesn't seem to work as expected. It appears empty even though I have tested it with the following code:

{{availabilities.length}} // result: 0
{{availabilities | json}} // result: []
// ngFor directive not displaying any data.

I'm curious about this behavior and wondering what data structure would be more suitable for this scenario (such as an indexed Array of objects).

Answer №1

If you are working with an associative array, one way to bind it is by using Object.keys. Here's an example:

// In your typescript file, define a property for Object.keys
objectKeys = Object.keys;
// In your HTML file, use objectKeys for binding
<ng-container ngFor="let key of objectKeys(arrayName)">
   <tr>
      <td>{{ arrayName[key].propertyName1 }}</td>
      <td>{{ arrayName[key].propertyName2 }}</td>
      ...
   </tr>
</ng-container>

Hope this explanation is helpful!

Answer №2

  • Correct the typo by changing disponibilites.length to disponibilities.length.

  • The data structure

    let disponibilities = ["2019-7-15" : {id: 1, ...},...]
    is incorrect (not an array or object). Please use:
    let disponibilities = {"2019-7-15" : {id: 1, ...},...}
    instead.

  • Replace disponibilites.length with

    Object.keys(disponibilites).length
    .

Answer №3

This could be the solution you are seeking:

availabilities = {
  "2019-7-15" : {id: 1, ...},
  "2019-7-16" : {id: 2, ...},
  "2019-7-20" : {id: 3, ...}
}

If you want to dynamically set the date key using a variable with ES6 ComputedPropertyName:

let date1 = "2019-7-15";
availabilities = {
  [date1] : {id: 1, ...},
  "2019-7-16" : {id: 2, ...},
  "2019-7-20" : {id: 3, ...}
}

Make sure to declare your array properly for Angular binding either without let or using this:

To iterate over it in the template, ensure Object.keys is accessible:

@Component({
  selector: 'app-myview',
  template: `<div *ngFor="let key of objectKeys(availabilities)">{{key + ' : ' + availabilities[key]}}</div>`
})

export class MyComponent {
  objectKeys = Object.keys;

  availabilities = {
    "2019-7-15" : {id: 1, ...},
    "2019-7-16" : {id: 2, ...},
    "2019-7-20" : {id: 3, ...}
  }

  constructor(){}
}

Answer №4

Unfortunately, this data structure may not be the most efficient as it does not allow easy access to objects by keys in JavaScript. Consider using the following alternative approach:

let disponibilities = [
  { date: "2019-7-15", id: 1, ...},
  { date: "2019-7-16", id: 2, ...},
  { date: "2019-7-20", id: 3, ...},
]

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

implementing a like button next to every item on a list using ajax

Help needed: How can I add a like button next to each item on my 'destinations' list? I'm struggling to figure out the placement. Any suggestions? Below is the content of my dashboard.html.erb file: <div class="destination-list"> ...

Error: module not found in yarn

https://i.sstatic.net/3zEMq.png In my yarn workspace, I have organized folders named public and server. While working with TypeScript in VS Code, I encounter an error message stating: Cannot find module 'x' Interestingly, even though the error ...

Sketch the borders of the element (animated)

Seeking a way to create a button with an animated border that looks like it is being drawn. Current progress involves some code, but it's not working smoothly with border-radius set. (keep an eye on the corners) https://codepen.io/anon/pen/MbWagQ & ...

How to build a customizable independent (No dependencies) service using Angular 15?

An injection token can be utilized to configure Angular services in a similar fashion. Nonetheless, it currently relies on the Module with Providers methodology for injecting configuration. Are there alternative methods available for configuring services ...

Having trouble getting your Bootstrap v4 carousel to function properly?

Currently, I have implemented the carousel feature from Bootstrap v4 in a Vue web application. I am following the same structure as shown in the sample example provided by Bootstrap, but unfortunately, it is not functioning correctly on my local setup and ...

Unable to access the newly created object's properties following the instantiation of a new resource in AngularJS

Currently, I am in the process of developing a new Resource utilizing AngularJS that falls under the category of Person. After successfully creating this resource, my goal is to retrieve the id associated with the new resource from the server. it('sh ...

Troubleshooting Ag Grid's Column Filter Refresh Problem

After making changes to the rows in an ag grid, the column filter values do not update accordingly. For example, The initial GRID rows are a b When the row b is deleted using the reload() method, the grid updates as follows a However, the column fi ...

Any new techniques for generating HTML content dynamically?

Although I have experience writing HTML, JS, and CSS pages, my current methods for adding, changing, or updating elements on a page feel outdated. I often resort to using cumbersome solutions like creating new windows or manually manipulating DOM elements. ...

Naming JavaScript properties based on array values

Can array values be transformed into property names for an object in a single line? For example: var arr = ['name', 'age', 'size']; To achieve: {'name' :null, 'age':null, 'size':null} Currently ...

Having trouble updating the input value in AngularJS?

As I venture into customizing an AngularJS tutorial on a Saturn Quiz, I am transforming it from multiple choice to a fill-in-the-blank quiz. The challenge I face is that the first answer registers as correct or incorrect, but subsequent questions always s ...

User IDs should not be shown on the jQuery datatable, although they are still accessible

I am wondering if there is a way to display certain user data in a datatable without showing the user id in the table itself. Here is my table: <table id="mitabla" class="display"> <thead> <tr><th>Last Name</th> ...

What are the downsides of using PHP redirects instead of JavaScript redirects, given that most large websites opt for the latter?

After closely examining the source codes of redirect pages on several major websites that redirect to their sponsors, I found an interesting pattern. Out of the five websites analyzed, four were using different Javascript redirects: <script type="text ...

Implement a recursive approach to dynamically generate React components on-the-fly based on a JSON input

My goal is to develop a feature similar to Wix that allows users to drag and drop widgets while adjusting their properties to create unique layouts. To achieve this, I store the widgets as nested JSON documents which I intend to use in dynamically creating ...

Sending all received parameters in a single request in Grails

In my Grails application, I am using the following JavaScript function: function sendPostRequest() { var projectNameFilter = $("input[name='project-name-filter']").val(); var addressFilter = $("input[name='address-filter&apo ...

Javascript: Issue encountered while the page was loading

Whenever I make an API call, an error keeps popping up every time the page loads. I can't seem to figure out why it's happening. Can anyone shed some light on this? I've tried to include the link: https://i.stack.imgur.com/3Ul0S.png This ...

Guide to utilizing Angular-charts efficiently

Recently, I attempted to utilize angular-charts from their documentation available at I successfully integrated angular-chart.js, chart.js, and angular-chart.css. Furthermore, I also included 'chart.js' in the angular module. However, I encounte ...

What is the best way to verify the existence of an email address?

I'm currently using the jQuery validation plugin and everything is working fine, but I've hit a snag when it comes to checking email addresses. The issue is that the plugin returns either true or false based on whether the email exists or not. Ho ...

Ways to attribute a numeric worth to a choice in a JavaScript form

I am in the process of creating a form that allows users to customize and order pizza while showing them the invoice as they make their selections. Currently, I have successfully implemented the display of user-selected options, but I am struggling with a ...

Pre-loading custom fonts in Next.js for a smoother user experience

I am currently utilizing next.js. My objective is to ensure that the fonts are loaded before any content is displayed on the screen. I attempted to achieve this by including them in the Head component within the _.document file using the rel="prelo ...

Is there a way for me to retrieve the variable from one function and use it in another

I have a tool for managing images with descriptions that allows me to edit both the text and the image file. The challenge is saving the modifications I make in my database. Currently, I can only save changes if I modify the image itself. If I only update ...