The @Input() property within an Angular component is producing an empty array as its result

I have a calendar component that has a data property marked as @Input():

import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-calendar',
  templateUrl: './calendar.component.html',
  styleUrls: ['./calendar.component.css']
})
export class CalendarComponent implements OnInit, OnChanges {
  @Input() data: CalendarDay[];

  constructor() {
    this.data = [];
  }

  ngOnInit() {
    this.initializeDays();
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log(this.data);
    console.log(changes.data);
  }
}

I send the data to this component like this:

<app-calendar [data]="this.calendarData"></app-calendar>

The passed data is then rendered using *ngFor in the calendar component (it renders perfectly and everything works smoothly):

<div *ngFor="let item of data">{{item.date}}</div>

Before rendering the data into the view, I want to parse it. However, whenever I try to log the data property within the calendar component, I get a strange array that appears empty at first but can be inspected further in the browser console:

.

When I attempt to log values like this:

console.log(this.data[0])

or

console.log(changes.data.currentValue[0])

I receive an undefined value.

Answer №1

Remove this.data = [] from the constructor to maintain consistency when utilizing dependency injection.

Instead, utilize set and get for each Input() that is intended for use in the template, as it follows best practices.

  private _data: CalendarDay[];

  @Input() set data(data: CalendarDay[]) {
    if(data) {
     this._data = data;
    }
  }

  get data(): CalendarDay[] {
    return this._data;
  }

When passing data into your HTML component, do so like this:

<app-calendar [data]="calendarData"></app-calendar>

In the calendar component, you can iterate over the data using:

<div *ngFor="let item of data">{{item.date}}</div>

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

Guide on making an SVG tooltip using the Menucool JS extension

I am trying to add a simple tooltip to an SVG "map" when the mouse hovers over a rectangle. To create the tooltip, I would like to utilize this specific plugin. Here is how I have connected the SVG to HTML: <object data="map.svg" type="image/svg+xml" ...

a versatile tool or JavaScript module for dissecting different HTML documents

Looking to develop a versatile wrapper or JS plug-in that can parse HTML content and locate tables within the files, allowing users to generate visual graphs like pie charts and bar graphs. The challenge lies in the fact that the HTML structure is not fixe ...

The ng-model binding does not automatically update another ng-model within the same object

Check out this code snippet: http://plnkr.co/edit/aycnNVoD96UMbsC7rFmg?p=preview <div data-ng-app="" data-ng-init="names=['One']"> <input type="text" ng-model="names[0]"> <p>Using ng-repeat to loop:</p> <ul> ...

Getting an Object in PostgreSQL without the need for square brackets wrapping when using Node.js and Express

I'm currently utilizing PostgreSQL alongside node-postgres: pool, Node.js, and express to execute some basic queries. The issue I encounter is that the returned object is wrapped within square brackets, but my preference is to receive it without them. ...

Prevent selection of specific weekdays in Kendo grid calendar

When editing a record in a Kendo grid with a date field, is there a way to only allow the selection of Monday and disable all other days of the week? ...

Node.js is raising an error because it cannot locate the specified module, even though the path

Currently in the process of developing my own npm package, I decided to create a separate project for testing purposes. This package is being built in typescript and consists of a main file along with several additional module files. In the main file, I ha ...

Display user account balances in real-time on the web browser by retrieving data from a secure private Ethereum

I am seeking to create a website that can display real-time updates of a user's wealth from a private Ethereum blockchain. Ongoing Issue (buggy) Currently, I have attempted to connect to a private Ethereum blockchain that is mining using a WebSocket ...

The issue arises when trying to use jQuery on multiple elements with the same class

Recently, I came across a jQuery script for my mobile menu that changes the class on click event. jQuery("#slide-out-open").click(function() { if( jQuery( this ).hasClass( "slide-out-open" ) ) { jQuery('#wrapper').css({overflow:"hidd ...

Tips for storing a JSON file with GridFS

In my possession is an extensive dataset. Utilizing mongoose schemas, each data element has a structure resembling the following: { field1: “>HWI-ST700660_96:2:1101:1455:2154#5@0/1”: field2: “GAA…..GAATG” } Reference: Re ...

The functionality of my Javascript code is restricted to a single element within a Python embedded for loop in Django2

My Python for loop is iterating through these HTML template cards, each accompanied by JavaScript. However, I'm encountering an issue where the JavaScript only seems to work on the first element (specifically, it's meant to retrieve the seeked po ...

Develop a search feature that automatically filters out special characters when searching through a

I am currently developing a Vue-Vuetify application with a PHP backend. I have a list of contacts that include first names, last names, and other details that are not relevant at the moment. My main query is how to search through this list while disregardi ...

Hide preloader in AngularJS once repeater has completed execution

Is there a way to hide a preloader div only after all data has finished loading in an ng-repeat loop? Check out this interactive example on Plunker: http://plnkr.co/edit/ilgOZzIy2axSi5Iy85C7?p=preview Here is the HTML code: <div ng-co ...

Instructions on how to sign up for a worldwide technique that is known as

I have a file called globalvars.ts where I added a global method. How can I subscribe to this method in the ts page where it is being called? globalvars.ts; httpgetmethod(url:string) { var veri; var headers = new Headers(); headers.append(' ...

Text about the three.js orthographic camera: "Exploring the

I'm trying to implement an orthographic camera overlay for a heads-up display on top of my main camera. I'm having trouble getting any text to show up, here's the code snippet: function setupHUD() { var width = window.innerWidth; var h ...

Streamlined Authorization in MEAN (SPA) Applications

I have created an application, but now I am trying to adapt it into a SPA application. The main issue I am facing is with the Authorization process. While I can successfully register new users, log them in, and retrieve their tokens, I seem to encounter a ...

Using AXIOS and VueJs to visually represent data with a two-dimensional array

I'm new to vuejs and I want to display my data response in a two-dimensional table. This is the data I have: [{ "origine": "", "nb": 15 }, { "origine": "?", "nb": 18 }, { "origine": "?L", "nb": 1 }, { "origine": "G", "nb": 298 }, { ...

The HTML element containing a React variable is failing to render ASCII characters

I am encountering an issue where a custom title, received and set in a JS variable, is displaying the ASCII code instead of the symbol. To illustrate, here is a basic example of the render function: render() { var title = "My Title&#8482;" retur ...

Personalized design for Material Tooltip in Angular 17

I am currently working on an angular 17 application that utilizes the latest Material components. My project heavily incorporates the Tooltip component, but I am facing challenges when it comes to customizing it to my preferences. While I did succeed in c ...

Map image showing only the tile layer in the top corner

My current project involves utilizing Ionic 5 and Vue.js. One of the screens in my project features a leaflet map that needs to cover most of the screen space. To implement this, I have integrated the Leaflet library for vue into my code. Here is a snippe ...

The map function is selectively applied to certain expressions, not all

Currently, I am attempting to display the genre Name and its corresponding gradient by utilizing the map function over an array called genres. While the map function successfully renders the genre Name, it seems to return the same component for the genre g ...