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

Is it possible to submit a POST method without using a form?

I am looking to create a button that functions similar to the "Follow" buttons found on social networks. The challenge I face is that I need to refresh the page when the user clicks the button, as the content of the page heavily depends on whether the user ...

Using Javascript, print the port number to the console

I am currently developing a small Electron app with node.js and I am facing an issue with outputting the port my application is connected to for development purposes. Below is my MySQL connection code snippet: const mysql = require('mysql'); c ...

Tips for updating the CSS properties of the "html" element

html { width:100%; } Looking to dynamically update the CSS of the html tag upon button click using JavaScript. The goal is to modify the existing HTML CSS code as shown below, but achieving this dynamically with a script. Is it possible? html { w ...

Enhancing React components with Hooks and markers

I'm facing a syntax uncertainty regarding how to update React state using hooks in two specific scenarios. 1) I have a state named company and a form that populates it. In the contacts section, there are two fields for the company employee (name and ...

Enhance your material-ui component using TypeScript functionality

Exploring ways to enhance the Material-ui Button component by introducing new props. The objective is to introduce a new prop called fontSize with three size options - small, medium, large. <Button variant="outlined" color="primary" ...

Encountering a Javascript error while trying to optimize bundling operations

After bundling my JavaScript with the .net setting BundleTable.EnableOptimizations = true;, I've encountered a peculiar issue. Here's the snippet of the generated code causing the error (simplified): var somVar = new b({ searchUrl: "/so ...

Creating numerous bar graphs for each specific date

I have a dataset containing dates and corresponding information for each element. Despite trying various approaches, I am unable to create a barchart. Every solution I've attempted has been unsuccessful thus far. The dataset is structured as follows ...

Using the onclick attribute as a unique identifier for a button

I am currently facing a challenge with a form that does not have an ID Here is the code snippet in question: <button class="btn btn-primary" onclick="showModal()" type="button">Browse Data</button> Unfortunately, I don't have any contro ...

What methods are available to pass a variable value between two components in Angular 2?

I've been experimenting with Angular2 and recently created a component called appmenu using angular cli. The code in appmenu.html looks like this: <ul> <li (click)="menuitem1()">Menu Item 1</li> <li>Menu Item 2</li> ...

Obtain pictures from MongoDB for a website using Angular6

I'm currently in the process of developing my website and I want to showcase an image from my database on the header. Each customer is assigned a unique logo based on their ID, but I'm unsure how to use Angular to display it. Below is my code s ...

Angular Error: The first argument has a property that contains NaN

Struggling with a calculation formula to find the percentage using Angular and Typescript with Angularfire for database storage. Encountered an error stating First argument contains NaN in property 'percent.percentKey.percentMale. The properties are d ...

Switching images dynamically using Flask and JavaScript

I'm currently working on Flask and encountering a perplexing issue. I'm attempting to update an image using JavaScript, but I am getting these errors from Flask: ... 12:05:34] "GET / HTTP/1.1" 200 - ... 12:05:38] "GET /img/pictur ...

What is the process for creating accurate types for my package?

Currently, I am in the process of creating an npm package to be used by other developers within my company. While most aspects are functioning smoothly, I am facing challenges with getting the declarations right. I have experimented with various methods f ...

The functionality of verifying the type of an item in a list using Typescript is not functioning

In my TypeScript code, I am working with a type called NameValue and another one called MixedStuff. type NameValue = { name: string; value: string }; type MixedStuff = NameValue | string; function stripTwoChars(stuffs: MixedStuff[]): string { let st ...

Concealing the parent view in Angular 2

I need to hide the above parent view. https://i.stack.imgur.com/CZFTn.jpg Here is my code. Upon clicking any of the boxes, the parent should be hidden and the child should appear. <app-navbar></app-navbar> <div class="cont ...

Experimenting with a TypeScript function containing a subscription operation

Currently, I am experimenting with Jasmine/Karma while working on an Angular 4 project. The issue I'm facing involves testing a function that seems to have trouble setting the 'name' property: https://i.stack.imgur.com/3q49i.jpg The assign ...

Inquiry regarding the return value of 'async-lock' in nodejs

I am utilizing the async-lock module in my typescript project to handle concurrency. However, I am encountering difficulties with returning the result within lock.acquire(...) {...}. Any guidance on how to resolve this issue would be greatly appreciated. ...

Creating a dynamic progress bar that scrolls for multiple elements

I am currently working on implementing a scrolling progress bar to show users how much of an article within a div they have read. For reference, something similar can be seen on this site. I have created my custom progress bar and coded it on fiddle, whe ...

Following the ajax request, the subsequent code was unable to be executed as it awaited the JSON response

My latest project involves using Django2 to create a web application. I encountered an issue in the frontend where, despite receiving a 200 status code in the network tab after an ajax call, no alert box was displayed. The app seemed to be stuck at a parti ...

Tips for properly invoking a function from one component to another component

After browsing through a few questions on the topic of parent/child elements, I have come across a particular node tree that looks like this: IndexPage -> Modals -> ClientDetails (it's modal component) -> Header My goal is to ...