Using Angular 5 to access a variable within a component while iterating through a loop

I am currently in the process of transferring code from an AngularJS component to an Angular 5 component.

Within my code, I have stored an array of objects in a variable called productlist.

In my previous controller, I initialized another empty array named showcaselist.

To filter out specific items that meet a certain condition (

item.acf.product_slide.length > 0
) from the productlist, I utilized a forEach loop and added them to the showcaselist. These filtered items are then displayed in the template.

Despite successful data retrieval and conditional statement execution confirmed by console logging, I keep encountering a console error:

TypeError: undefined is not an object (evaluating 'this.showcaselist')

Below is the complete code snippet for the component:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';


@Component({
  selector: 'pb-ds-showcaseindex',
  templateUrl: './showcaseindex.component.html'
})
export class ShowcaseindexComponent implements OnInit {

  productlist;
  showcaselist = [];

  constructor(private _route: ActivatedRoute) { }


  ngOnInit() {
    this.productlist = this._route.snapshot.data.showcases;
    this.itemsWithSlides();

  }

  itemsWithSlides = function () {
    this.productlist.forEach(function (item) {
      if (item.acf.product_slide.length > 0) {
        this.showcaselist.push(item);
      }
    });
  };
}

Answer №1

If you want to make it more concise, consider utilizing the filter() method.

class ShowcaseindexComponent implements OnInit {
  productlist;
  showcaselist = [];

  constructor(private _route: ActivatedRoute) { }

  ngOnInit() {
    this.productlist = this._route.snapshot.data.showcases;
    this.showcaseList = this.productList.filter(item => item.acf.product_slide.length > 0);
  }
}

Answer №2

Consider this solution:

onInit() {
    this.showcases = this._route.snapshot.data.showcases;
    this.filterItemsWithSlides(this.showcases);
}

private filterItemsWithSlides(showcases) {
  if (showcases) {
    showcases.forEach(item => {
      if (item && item.acf.product_slide.length > 0) {
        this.filteredShowcases.push(item);
      }
    });
  }
}

Answer №3

Consider using an arrow function instead. The current function is generating a new this that points to a different object.

  obtainItemsWithSlides = () => {
    this.productlist.forEach((item) => {
      if (item.acf.product_slide.length > 0) {
        this.showcaselist.push(item);
      }
    });
  };

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

What is the method for altering the state of a single element within a map?

As I delve into learning React, I encountered a persistent issue that has been absorbing my time for several hours now. The problem revolves around mapping an array of product sizes to buttons and controlling the state change of only the last clicked butto ...

Utilize a viewpoint alteration alongside a floating effect on a specific element

I thought this would be an easy task, but I seem to be missing something as it doesn't work for me. The goal is to use the perspective() and rotateY() functions in a transform to create a perspective effect on an element. Additionally, there should b ...

What is the best method for transmitting server errors to the client?

When using passport.js, I have all the required code in place. However, I am facing an issue with displaying errors on the client-side. Despite having the successRedirect set up correctly, nothing happens when a wrong password is entered, and no error mess ...

Leverage the power of Web Components in Vue applications

Currently, I am attempting to reuse Web Components within a Vue Component. These Web Components utilize the template element for formatting output. However, when I insert them into the Vue Template, they are either removed from the DOM or compiled by Vue. ...

Using jQuery, generate a dynamic form to create a multidimensional array

I've set up a form where additional dropdowns can be dynamically added if the user clicks on a specific link. Here's an example of how it looks: <div class="dynamic-sale"> <select name="sizes[]" id="sizes" class="entry-dropdown"&g ...

Executing an ajax post when a user clicks on a link or button

<tr> <td> <span id="id_1"> <a href="/Path" >Name</a> <a href="#">Delete</a> </span> </td> &l ...

Showing elapsed time similar to YouTube in an Angular 8 application

Currently, I am developing an Angular application to replicate certain features found on YouTube by utilizing data fetched from an API. This API provides video timestamps in a string format Each timestamp follows this structure : YYYY-MM-DDTHH:MM:SS For ...

Automatically scrolling down a div as new content is added using XMLHTTPRequest.openConnection

https://jsfiddle.net/kv5gbamg/ - I created a jsfiddle to demonstrate the functionality of the system Essentially, I am seeking a way to automatically scroll the scrollbar to the bottom every time a new message is received. My system updates the div with ...

Troubleshooting Angular 4 Routing Problems

I am facing an issue with Angular where the components I configure to load at the empty '' path are not rendering properly. Below is a breakdown of my project structure: project/ |- app/ | |- landing-page/ | |- second-page/ | |- third-pag ...

sending the properties from the menu component to the dish details

Having trouble with a react.js app I'm working on that involves rendering dish cards. The dish object is always null when passed as props from MenuComponent to DishDetail, resulting in nothing being displayed on the screen. Can someone please assist m ...

Why is the removal of this type assertion in TypeScript causing an issue?

Why is TypeScript refusing to compile this code snippet? interface TaggedProduct { tag: string; } interface Product { tag?: string; } const tagProduct = (product: Product): TaggedProduct => { const tag: string = "anything"; pro ...

Tips for verifying that input is provided in a text field when the checkbox is marked

Can someone help me with validating a form where the user must enter data in a text field if they check a checkbox? I have JavaScript code for checkbox validation, but need assistance with text field validation. Thank you! $(document).ready(function () ...

Issue with FusionCharts rendering correctly arises when the <base> tag is present in the HTML head section

Combining AngularJS and FusionCharts in my web application has led to a unique issue. The upcoming release of AngularJS v1.3.0 will require the presence of a <base> tag in the HTML head to resolve all relative links, regardless of the app's loca ...

Conceal a row depending on the value in a specific column

After reviewing the data in the table provided: +-----------------------+-----------------+---------------+ | 212 | fred | red | +-----------------------+-----------------+---------------+ | 230 ...

Incorporating a counter feature into an Angular HTML document

In this section, I am displaying the restaurants that are filtered based on their name and address. If no name or address is provided, all restaurants are shown. However, I am facing an issue as I need to incorporate a counter to keep track of the remainin ...

How to retrieve the button value in HTML

One of the HTML components I am working with is a button that looks like this: <button>Add to cart</button> My goal is to retrieve the text within the button, which in this case is "Add to cart." To achieve this, I need to extract this value ...

Javascript - Button animation malfunctioning after first click

One issue I'm facing is with an animation that is triggered using the onmousedown event. Another function is supposed to stop the animation when onmouseup is detected. The problem arises after the first time it works correctly. Subsequent attempts to ...

Automatically modify browser configurations to disable document caching

Is it possible to prevent browsers from caching pages using JavaScript? I've noticed that even though PHP has a redirection implemented once the user logs in, when they press the browser's history button, it goes back to the login form. This is b ...

What kind of Input field is being provided as an argument to a TypeScript function?

Currently, I am working through an Angular 2 tutorial where an input element is being passed to a function through a click event. The tutorial includes an addTodo function with the following signature: addTodo(event, todoText){ }. However, there is a warn ...

Fetching the exchanged messages between the sender and recipient - utilizing MongoDB, Express, and React for chat functionality

I am dealing with two collections named students and teachers in the mongodb database. The structure of a conversation between a student and a teacher involves arrays of messages within each object, as well as the IDs of the sender and receiver. I am seeki ...