The Angular MatStepper is unable to detect saved values from two string arrays, although it is able to detect values from a different string array

In my application, there is a MatStepper component that facilitates navigation through the signup flow. A method exists to load cached values when available, causing the MatStepper to skip to Page 2. Subsequently, another method pre-fills the form with these cached values.

The issue arises when attempting to pre-fill the form with either cachedPets or cachedAnimals, resulting in an error on the MatStepper:

Cannot read properties of undefined (reading 'next')

Despite similarities between cachedSports and the failing scenarios, all being arrays of strings with successful cache retrieval, I am unable to identify the cause of the problem.


// Code snippet for loading cached values from memory-cache.service.ts
loadFromCache(): void {
    const cachedPets: string[] = this.cacheService.get<string[]>(MemoryCacheService.WellKnownKeys.pets) ?? [];
    const cachedSports: string[] = this.cacheService.get<string[]>(MemoryCacheService.WellKnownKeys.sports) ?? [];
    const cachedAnimalNames: string[] = this.cacheService.get<string[]>(MemoryCacheService.WellKnownKeys.animals) ?? [];

    if (cachedPets.length > 0) {
      // Logic to set targeting form group based on cached values
    } else if (cachedSports.length > 0) {
      // Logic to set targeting form group based on cached values
    } else if (cachedAnimalNames.length > 0) {
      // Logic to set targeting form group based on cached values
    }

    console.log('cachedPets: ', cachedPets);
    console.log('cachedSports: ', cachedSports);
    console.log('cachedAnimalNames: ', cachedAnimalNames);

    this.goForward(); // This triggers the 'next' action on MatStepper

    // More logic here to handle cache removal and other actions
}

goForward(){
    this.myStepper.next();
}

This section handles the validation of targetting form


// Code for validating targeting form within the same file

validateFormTargeting() {
  
  // Some logic to validate form values
    
}


Error message details:

TypeError: Cannot read properties of undefined (reading 'next')
    at AppModalFormCreateComponent.goForward (myForm.component.ts:371:20)
    at AppModalFormCreateComponent.loadFromCache (myForm.component.ts:357:10)
    at AppModalFormCreateComponent.ngOnInit (myForm.component.ts:227:10)

Answer №1

The issue lies in the ViewChild not being properly defined or set when the method goForward is invoked.

If the template is being modified, it could be a timing problem. To troubleshoot, consider encapsulating the code within the goForward method inside a setTimeout().

Answer №2

It is important to ensure that your code runs only after ngAfterViewInit, as there may be instances where you try to access an element before the view has been rendered. This can lead to an undefined property for the ViewChild queried on the view.

PLEASE NOTE: While ngAfterViewInit may not always be the ideal lifecycle option, it is essential to select the most appropriate one from the list provided in the following link: https://angular.io/guide/lifecycle-hooks

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

There appears to be a JavaScript validation error occurring on the current page, however, you are able

For my datepicker, I want an error message to display if the user selects a date more than 5 years in the future, saying "You are ineligible for our program". The user should not be able to proceed to the next step unless this error message is ad ...

Leverage the Axios package to make requests within a for loop

I'm new to JavaScript and currently working on a project using Vue.js, Axios, and the API available at . The goal of this project is to retrieve NBA player statistics for a homework assignment. I could use some assistance in addressing certain issues. ...

Faulty deduction can occur when implementing the return statement in an identity function, or when incorporating an optional parameter

Encountering strange behavior while working on identity functions in a wizard system schema. Using a constrained identity function for inference is causing issues with one property that cannot be inferred when using the following: When the return value fr ...

What to do when faced with the error message "Nodemon is not recognized as a command"?

When I try to run npm start, my Node.js is not starting. The error message displayed is: 'nodemon' is not recognized as an internal or external command, operable program or batch file. I have double-checked my environment path and also tried r ...

When Google Chrome encounters two variables or functions with the same name, how does it respond?

I am curious what happens when Google Chrome encounters two variables with the same name. In my particular case, this issue arises in the code snippet available at this link, which is a small portion of the entire code. I am facing an issue where placing C ...

How can I remove markers from google maps?

I have been working on a program that dynamically loads JSON data onto a map as markers when the user pans and zooms. However, I am facing an issue where I need to clear the existing markers each time the user interacts with the map in order to load new on ...

Please provide me with the coordinates (latitude and longitude) for that address

I am looking to integrate the Google geocoder into my website. I want to be able to input any location address and receive the latitude and longitude coordinates for that location. Are there any helpful tutorials available? For reference, I found a simila ...

Steps to troubleshoot a simple function that manages asynchronous tasks

Looking to develop a versatile function that can handle async functions, execute them, and catch any errors that may arise. Coming from a javascript background, I initially managed to create a function that did just this. However, my attempt to enhance it ...

What is the best way to implement a date range filter in AngularJS for a specific year or month?

I am just starting to learn AngularJS. I have a date formatted as follows: d MMM y. However, I have two fields - one called "from" and the other "to" - that should act as filters for the date range, based on a year range or month range. Here is how I am or ...

The context of the selector causes an error to be thrown

Why does jQuery throw an exception when I attempt to select an element with context? The code is as follows: jQuery('b', "DAS<br/><br/><b>ID</b> = 02<br/><b>NAMA DAS</b> = CITARUM<br/><b>LUAS ...

Responsive Grey Tiles for Google Maps v3

I've successfully implemented Google Maps V3 in my project, but I'm encountering an issue with grey tiles appearing on the map. I attempted to fix this problem by triggering a resize event using the following code snippet: google.maps.event.trig ...

Unable to retrieve data following a promise in Ionic 3

Hello, I'm currently working on an Ionic application that needs to display data in a Form Group after retrieving it with a SOAP ReadData request. Although I call my function and try to display the data in the form, there seems to be an issue as the f ...

Angular Material 2 Stepper Controls for Angular applications

I successfully implemented a linear stepper using the Angular Material 2 Stepper component. My project consists of forms in various components (component-a, component-b, component-c). I need the linear stepper in my main container component (container-com ...

Tips for showcasing a Bootstrap alert

I'm attempting to integrate Bootstrap Alerts into my project, but I'm struggling to display them programmatically. Here is the HTML snippet: <div class="alert alert-success alert-dismissible fade show" role="alert" id="accepted-meal-al ...

Experiencing problems with malfunctioning javascript tabs

As a beginner user and coder, I'm currently working on creating a portfolio website. I had the idea to implement tabs that would allow for content swapping, but unfortunately, I'm having trouble getting the JavaScript to function correctly. I at ...

Is NX capable of speeding up the performance of ng serve?

Just starting out with NX... NX is designed to enhance the Angular CLI by leveraging computation caching for faster performance. When using nx build, builds are completed almost instantly thanks to caching. However, I'm curious if nx serve also uti ...

Having trouble getting Vue to properly focus on an input field

I am attempting to use this.$refs.cInput.focus() (cInput being a ref) but it seems to not be functioning as expected. I expect that when I press the 'g' key, the input field should appear and the cursor should immediately focus on it, allowing me ...

Load the React component asynchronously while waiting for the data to be fetched

My ReactJS component looks like this: import React, {useState} from 'react'; import Plot from 'react-plotly.js'; import {utility} from "./utility"; function Chart() { const [use_data, setData] = useState([]); c ...

### Setting Default String Values for Columns in TypeORM MigrationsDo you want to know how to

I'm working on setting the default value of a column to 'Canada/Eastern' and making it not nullable. This is the current setup for the column: queryRunner.addColumn('users', new TableColumn({ name: 'timezone_name', ...

Is it not possible to utilize inline "if" statements in conjunction with useEffect within a functional React component?

I'm currently working on integrating Okta's React SDK into a TypeScript-based application using functional components instead of class-based ones. My main challenge lies in rendering a part of the app's menu based on the user's authenti ...