I'm encountering difficulty reading a property of undefined in my Angular code, despite having properly initialized it

While working on creating filters with 3 categories, I came up with a Model:

export class filtersApplied {    
    public subjects: string[] = [];
    public price: string[] = [];
    public ratings: number[] = [];
 }

Whenever a user applies filters from any of these categories, I want the chosen values to be added into their respective arrays in the model. For example, if I select "ENGLISH", "MATHEMATICS", and "SCIENCE", I would like them to be inserted into the "filtersApplied.subjects" array for processing at the backend.
allFiltersApplied is a variable of type filtersApplied.
allFiltersApplied: filtersApplied;

 <ul class="filter-category-list">
                <li>
                    <label class="filters-label">
              <input
                type="checkbox"
                class="filter-input"
                value="English"
                (change)="searchBySubject($event)"
              />English
              <span class="filter-num">(123)</span>
            </label>
                </li>
           <!-- more list items -->
</ul>

This is the function in my TypeScript file:

 searchBySubject($event) {
        var subject = $event.target.value;
        console.log(subject); //1
        console.log(this.allFiltersApplied); //2
        console.log(this.allFiltersApplied.subjects); //3
      }

The output I received for console.log(this.allFiltersApplied) is undefined; The output I received for console.log(this.allFiltersApplied.subjects) is Cannot read property 'subjects' of undefined at SearchResultsComponent.searchBySubject;

**I Have Some Questions:**
1. Why is it displaying undefined?
2. Why can't it read subjects when they are already defined? I am unable to push any value such as this.allFiltersApplied.subjects.push("ENGLISH");

I Request Your Assistance on this matter, as I am unclear about the behavior exhibited.

Answer №1

It appears that allFiltersApplied is being treated as a variable, but it is more likely intended to be a property of a class. In JavaScript, variables are declared using const, let, or var.

If you have defined it within a class like this:

export class MyClass {
  allFiltersApplied: filtersApplied;
}

it means the property has been declared but not assigned any value yet, so its current value would be undefined.

Declaring a specific type for a property ensures that it is used according to the specified type when utilized.

To initialize the property with an initial structure similar to filtersApplied, where arrays can store values, you need to instantiate it as follows since filtersApplied is a class:

export class MyClass {
  allFiltersApplied: filtersApplied = new filtersApplied();
}

If you had defined it as just a type for typing purposes and not a complete class definition, you can initialize the property in the following way:

export class MyClass {
  allFiltersApplied: filtersApplied = {
    subjects: [],
    price: [],
    ratings: []
  };
}

A couple of additional points to consider:

  1. The convention for naming classes and types suggests using UpperCamelCase, so filtersApplied should potentially be named FiltersApplied for consistency.
  2. Making negative comments towards individuals offering assistance, such as those made towards @Pointy who has a reputable reputation on this platform, may discourage future help from others.

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

Tips for retrieving usercontrol value in JavaScript/jQuery

Imagine that I have created a user control with two textboxes and one button --Start UserControl Details-- <asp:TextBox runat="server" id="txtName"></asp:TextBox> <asp:TextBox runat="server" id="txtAddress"></asp:TextBox> --End ...

Performing a single AJAX call from a JavaScript loop is more efficient than iterating through multiple AJAX calls

I am working with a 2D array in JavaScript. Currently, I have a for loop where I make an AJAX call to update the database. I understand that this approach is not efficient, and I am seeking a way to update the database with just one AJAX call within the ...

I am encountering an issue where req.body is returning as undefined

After creating a controller with the code below: app.post('/users', (req, res) => { console.log(req.body); const user = new User({ name: req.body.name, email: req.body.email }); user.sa ...

I'm attempting to showcase the keyName and pattern for the arrays of Objects in Keyless and Keypresent in AngularJS, but unfortunately, I'm facing some issues

let information = { headerFields: { noKey: [{ key1: { name: "test1" }, key2: { name: "test2" }, key3: { name: "test3" } }], hasKey: [{ key1: { name: "test4" } ...

Issue with AddToAny plugin not functioning properly on FireFox

I’m having issues with AddToAny for social media sharing on my website. It seems like FireFox is blocking it because of tracking prevention measures. Error Message in Console: The resource at “https://static.addtoany.com/menu/page.js” was blocked d ...

Tips on sending form data, including a file, to Ajax using the onclick() method

My Modal Includes a Form: <div class="modal fade bs-example-modal-lg" id="myMODALTWO" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" id="form-content"> <div class="modal-dialog modal-lg" role="document"> ...

JavaScript's regular expression does not fully match until the end of the given string

In my JavaScript code, I am validating dates using a regular expression. The specific regular expression I am utilizing is as follows: /^(((((0?[1-9])|(1\d)|(2[0-8]))\/((0?[1-9])|(1[0-2])))|((31\/((0?[13578])|(1[02])))|((29|30)\/((0?[1 ...

Retrieve the user_id without triggering any route

Is there a way to access the logged in user data without needing to make a request to any route or endpoint? //for example, how can I retrieve the id of the logged in user here? router.get('/',function(req,res,next){ //typically we would acce ...

Refining search results with dynamic filter conditions in TypeScript array objects and using search refiners in SharePoint

In my Typescript and SharePoint Search project, I am working on a scenario involving a Collection of Arrays structured as follows: let _SelectedBusinessUnits =[ { "fileName": "XYX.doc", "Region": "APAC", "Country":"Australia;China", "LOB": "Auto;Busines ...

Developing a standard jQuery function for adding event listeners

Attempting to replicate the functionality of Google Maps' addListener using jQuery listeners for clicks, keypresses, etc. In Moogle Maps, you can use .event.addListener(map, 'click', function()... or switch 'click' with 'drag ...

Creating Dynamic Graphs using Angular and Chart.js with Array Values

I have implemented ChartJS-2 to visualize a graph displaying an array of user activities, but it appears distorted: import { Component, OnInit, Input } from '@angular/core'; import { ChartOptions, ChartType, ChartDataSets } from 'chart.js ...

HTML login form featuring a transparent design with a username textfield already populated with a cookie

Hey there! I'm in the process of creating a simple website for my university. I need to include a login form where users can enter their username and password. If the credentials are correct, a cookie is set with the username value. This way, when the ...

Exploring the functionality of two-way data binding in Angular - a beginner's guide

Transitioning from a different framework and switching from JavaScript to Angular & TypeScript has left me feeling confused about how to efficiently share data/values between components. ...

Encountered a session.socket.io error: unable to find session using the provided key: connect.sid

So, I've been struggling with an issue for the past couple of days and I can't seem to figure it out. I've searched through various resources like this GitHub issue and Stack Overflow, but I still haven't found a solution. Here's m ...

The error message "Joomla! 2.5 and Virtuemart 2.0.18a - $.facebox is not recognized"

I encountered an issue while using Joomla! 2.5.8 and Virtuemart 2.0.18a where I received the error message "Typeerror $.facebox is undefined in vmprices.js (line 67)" when attempting to Add to Cart. Interestingly, switching back to the default Joomla! temp ...

React is unable to identify the prop `controlID` when used on a DOM element in React-Bootstrap Forms

While constructing a form with React components sourced from react-bootstrap, and taking guidance directly from an example provided in its documentation: <Form.Group controlId="formBasicEmail"> <Form.Label>Email address</Form.Label> ...

Gallery of images resembling Getty Images without the use of a database

I want to put together an image display, similar to the functionality on Getty Images where clicking on an image brings up more details. Here is an example link from Getty Images: The image I am working with can be found here: All I need is a way to nav ...

How can I make <p> elements change color when scrolling?

My Goal https://i.sstatic.net/JbdXR.gif I aim to bring attention to the <p> element as the user scrolls on the page. Initially, the opacity is set to 0.3, but I want it to change to 1 gradually as the user scrolls down. My Attempt window.o ...

What is the best way to display two columns in each row using Angular?

Can you please provide guidance on how to display two columns in each row using Angular? I am attempting to showcase only two columns per row, and if there are more than four items, I want to display them on an ion-slide. Further details will be provided. ...

How can I display a "loading..." message as a temporary placeholder while waiting for my Apexcharts to load?

I've spent a day trying to solve this issue but couldn't find a solution. Any help would be greatly appreciated. Recently, I was working on creating a cryptocurrency tracker in React. I successfully built a table that displays multiple currencie ...