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

(node:2824) UnhandledPromiseRejectionWarning: ReferenceError: The variable "role" has not been declared

I am currently in the process of getting my discord bot up and running again. The issue is that he is old, and in the previous version, this functionality worked. However, after reading other posts, I discovered that in order to make it work, I need to u ...

How can I properly reset a timeout duration?

I'm currently working with a function that looks like this: function blabla(){ ... setTimeout(() => { //do some stuff }, 10000) } My question is, how can I reset the time of the timeout (10000) if the function was called and ...

Conceal the second click action within the anchor tag

Is there a way to hide the second click event on all anchor tags except those that trigger popupfun? I have a sample page set up. [Check out the JS Fiddle here][1] http://jsfiddle.net/ananth3087/LgLnpvf4/15/ Link Anchor Tags: The page includes two ...

Unforeseen outcomes when setting background colors with Anime.js

I've recently started experimenting with Anime.js. I have a piece of code that I'm using to animate a div element with an id of a. anime({ targets: "#a", translateX: 250, color: "#fff", backgroundColor: "hsl(200, 50%, 50%)", ...

What is the correct syntax for declaring a variable within a switch statement in TypeScript?

How can I properly use a switch statement in TypeScript to assign a new variable a value? For example: let name: string switch(index) { case 0: name = "cat" case 1: name = "dog" .... } I keep getting the err ...

What is the best way to set multiple headers and change the content type when needed?

I am struggling with a function that cannot be overridden: getHtml:function(aURL,aPostData,aHeaders,aMethod){ this.xhr = new XMLHttpRequest(); var tmp=this; this.xhr.onreadystatechange=function(){ tmp.onStateChange(); }; if(aPo ...

The error encountered during parsing the module for Next.js, Webpack, and TypeScript files (.ts, .tsx) was due to an unexpected token

Here is the content of my next.config.mjs file: export default { webpack: (config) => { // Find rules that includes current directory const rulesWithCurrentDir = config.module.rules.filter((rule) => rule.include && rule.include.incl ...

The fixed header option is not available for the CdkVirtualScrollViewport

Looking for a solution in my Angular application where I need to keep the table header at a fixed position while displaying the scrollbar only on the body part. Currently, I am utilizing the CdkVirtualScrollViewport library in Angular to render the table c ...

You are required to select one of the two radio buttons in order to proceed with the validation process

To prevent the user from proceeding to the next page, validation is necessary. They are required to select one of the radio buttons, etc. <div class=""> <div class="radiho" style="display: block"> <input type="checkbox" name="sp ...

Is there a way to restrict props.children.some to only accept image types?

Currently troubleshooting the following issue: An error is occurring: 'Property 'type' does not exist on type 'true | ReactChild | ReactFragment | ReactPortal'. Property 'type' does not exist on type 'string'. ...

Creating a function that uses setInterval to continuously update the input with a specific value

I am looking to use the setInterval function to continuously update the value of #test1. Additionally, I want the value of #test1 to be cleared and reset to 1 second after the user clicks a button. Example output can be found here: http://jsfiddle.net/eK ...

Declining the request to incorporate an external website into my web platform

While checking the console errors in Google Chrome, I encountered the following error message: The page 'https://website.com' was blocked from framing because a higher-level ancestor violates the Content Security Policy directive: "frame-an ...

When using Javascript, an error is being thrown when attempting to select a nested element, stating that it is not a function

I am facing a challenge in selecting an element within another element, specifically a button within a form. Typically, I would use jQuery to achieve this as shown below: element = $('#webform-client-form-1812 input[name="op"]'); However, due t ...

How to Stop AJAX Requests Mid-Flight with JQuery's .ajax?

Similar Question: Stopping Ajax Requests in JavaScript with jQuery Below is the straightforward piece of code that I am currently using: $("#friend_search").keyup(function() { if($(this).val().length > 0) { obtainFriendlist($(this).va ...

splitting the array elements in JavaScript

I'm having trouble with my code that is supposed to separate the array in customer and customerportals. let j = 0; let k = 0; let myVar = []; $.each(Object.customer, function(index, value) { $.each(value.portal.customerPortal, function(innerIn ...

What is the best way to manage a debounced event emitter in Cypress using RxJs debounceTime?

My task involves creating tests for a web page containing a list of items and a search-filter feature. The search-filter functions by filtering the list of items based on the input entered into its text field. Whenever the value in the text field changes, ...

An issue arises when ng-pattern fails to recognize a regular expression

My form includes inline validation for a specific input field. <form name="coForm" novalidate> <div> <label>Transaction: </label> <input type="text" name="transaction" class="form-control" placeholder="<Dir ...

Unknown Parameters Issue with Vue.js Router Links

Within my Vue.js project, I am utilizing params in my navigation.vue component to pass data onto the next page for dynamic routing purposes. Below is an example of how I am using this: <router-link tag="p" :to="{name: 'Main', ...

Failing to include a valid string in the path will result in an

Within my node API, I have a function that updates the email address array for either a contact or a farm. The concept is the same, but the difference lies in where the array is located: in farms it's within Records.emails, and in Contacts it's s ...

Refresh page upon clicking the same state link in AngularJS using ui.router

Just received an interesting request from our QA team that seems a bit out there. Let's dive in: imagine you are already on the 'about' state/page within an angular-based app, and when you click on the 'about' state URL again from ...