The property 'nometape' cannot be assigned to an undefined value

Currently, I'm encountering an issue in my Angular 7 code where it states "cannot set property 'nometape' of undefined." The problem lies within the initialization process of my interface "Process" which contains an array of objects called "Etape." Here are the interfaces:

export interface Process {
    id : string,
    etapes : Etape[],
} 
export interface Etape {
    nomEtape : string,
    ordre : number,
    etat : number,
    remarque : string,
    duree: string;
    dateRDV : Date,
}

The object declaration looks like this:

  proEdit : Process = {
  id: "",
  etapes : [] 
}

To initialize the process etapes array, I use the constructor with the following:

this.proEdit.etapes = [{
         nomEtape : " ",
         ordre : 0,
         etat : 0,
         remarque : "",
         duree: "",
         dateRDV : new Date(),
       }] ; 

The problem arises when I loop through the etapes array, resulting in the error message "cannot set property 'nometape' of undefined."

editProcess(){
   for(let i = 0; i < this.productForm.value.etapes.length; i++) {
     this.proEdit.etapes[i].nomEtape = this.productForm.value.etapes[i]["step"];
   } 

Answer №1

It seems like the issue may not be caused by the initialization process, as you mentioned. My guess is that the problem lies in the fact that the array at index i is undefined. Have you added a new Etape object to this.proEdit.etapes?

Instead of simply setting the value at index i, have you considered trying something like this? While I cannot guarantee it will work, the concept is to add a new element to the array rather than replacing an existing one.

const newEtape: Etape = {
  nomEtape : this.productForm.value.etapes[i]["step"],
  ordre : 0,
  etat : 0,
  remarque : "",
  duree: "",
  dateRDV : new Date(),
};

this.proEdit.etapes.push(newEtape);

Answer №2

The initialization code for this.proEdit.etapes currently only places a single element in the array. This may result in an error if this.productForm.value.etapes contains more than one element.

A better approach would be to create a method within the proEdit object that can synchronize an array of step values with its internal etapes array.

You can consider implementing something like the following code snippet (assuming you have lodash zip or a similar alternative):

const makeNewEtape = (step: string, etape: Etape | Object = {}): Etape => ({
  // Default values
  ordre : 0,
  etat : 0,
  remarque : "",
  duree: "",
  dateRDV : new Date(),

  // Override defaults with existing Etape values
  ...etape,

  // Override any existing nomEtape value
  nomEtape : step,

});

class ProSteps {
    private etapes: Etape[] = [ makeNewEtape(" ") ];

    syncEtapes(steps: string[]) {
      this.etapes = zip(this.etapes, steps)
        .filter(([ , step]:[ Etape,string]) => !!step)
        .map(([etape, step]:[Etape, string] ) => makeNewEtape(step, etape));
    }

    getEtapes() { // Ensure no direct access to the array
      return [...this.etapes]
    }
}

const ps = new ProSteps();
ps.syncEtapes([ 'foo', 'bar', 'baz']);

Feel free to explore and experiment with this code on the provided StackBlitz.

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

Switching from callback to function in TypeScript

Currently, I am utilizing the mongodb driver to establish a connection with mongo: public listUsers(filterSurname?:string):any { if (this.connected) { debug.log(this.db); var results; this.db.collection(' ...

How can I extract fields from a response using Axios?

I came across this code snippet: axios.get<Response>(url) .then(response => { console.log(response.data); }).catch(error => { // handle error console.log(error); }); The JSON response I am receiving has fields that are not easily e ...

Determine whether one class is a parent class of another class

I'm working with an array of classes (not objects) and I need to add new classes to the array only if a subclass is not already present. However, the current code is unable to achieve this since these are not initialized objects. import {A} from &apo ...

How can I inform Typescript that a function will never return null in this specific scenario?

Need help with implementing typescript strictNullChecks in an Angular 5 project. The form structure is as follows: this.signinForm = this.fb.group({ emailAddress: ['', NGValidators.isEmail()], password: ['', Validators.required], ...

Value attribute property binding

Currently, I am diving into the world of Angular 5 and focusing on grasping the fundamentals. One concept that caught my attention is template reference variables. However, I encountered a roadblock along the way. Instead of utilizing a template reference ...

Can a function cast an object automatically if it meets certain conditions?

Imagine having an object that has the potential to belong to one of two different classes in a given scenario: const obj: Class1 | Class2 = ... if ( checkIfClass1(obj) ) { // obj = <Class1> obj ... } else { // obj = <Class2> ...

Can an attribute be assigned to an Angular host element without specifying a value?

Exploring the concept of host binding on the input element's readonly attribute, aiming to add the attribute without assigning any value. Even though HTML specifications state that assigning a value may not make a difference as long as the attribute i ...

Leveraging an intersection type that encompasses a portion of the union

Question: I am currently facing an issue with my function prop that accepts a parameter of type TypeA | TypeB. The problem arises when I try to pass in a function that takes a parameter of type Type C & Type D, where the intersection should include al ...

Angular 8 is encountering an issue with an undefined global variable, specifically the variable "this

I have a model named Chat, defined as follows: export class Chat { chatId?: number; chatUser1?: string; chatUser2?: string; chatStatus?: string; created_at?: any; updated_at?: any; deleted_at?: any; } In the component, I need to retrieve the value of ch ...

A guide to effectively unit testing StripeJs within the Karma testing framework for Angular 8

I'm currently facing a challenge in unit testing a payment component that relies on StripeJS. In my 'ng-app.js' file, I import it as follows: stripe: /*@ngInject*/ function ($ocLazyLoad) { return $ocLazyLoad.load({ ...

Managing various control forms to be processed individually within Angular's Reactive Forms system (Clean Code)

I am currently working with Angular 11.0.2 and have a form group containing 20 fields that are displayed in two tables. Some of these formControls are shared between two forms. There are approximately 9 text input fields that I want to monitor for value c ...

Whenever the condition is met, it will always be executed

I'm attempting to conditionally execute an if statement based on a Boolean value within an object in my database. However, it always seems to run regardless of the value. Since I'm new to TypeScript, it's possible that I'm overlooking s ...

Choose a specific child element to be repeated within an ngFor loop in the parent component

I have a collection of mat-expansion-panels listed in the HTML below. Users can dynamically add as many panels as they want by clicking the "ADD RESOURCE" button. Parent Component HTML <mat-accordion> <ng-container *ngFor="let it ...

Transforming JavaScript into TypeScript - school project

After researching similar questions and answers, it appears that any valid JavaScript code can also be considered TypeScript? If this is true: const express = require('express'); const bodyParser = require('body-parser'); const ...

Guide to encapsulating an angular material form within a component and making it accessible to the FormGroup as a formControl property

My goal is to create a custom component (let's call it custom-input) that acts as a formControl element using Angular material components. It should include the following structure: <mat-form-field > <input matInput [formControl]=" ...

Repeating promises resolutions yields stagnant outcomes

Within my Angular project, I am working with two distinct components. parent.component.ts mypromise = this.httpClient.get<any>('http://localhost').toPromise() parent.component.html <app-children #child [promise]="mypromise"></a ...

Access route information external to the router outlet

Can we access the data parameters in a component that is located outside of a router outlet? const appRoutes: Routes = [ { path: '', component: SitesComponent }, { path: 'pollutants/newpollutant', component: PollutantComponent, data: { ...

What is the process for accessing product information on a separate page?

I'm a beginner in Angular and I'm working on creating a simple ecommerce page. So far, I have developed a homepage where I fetch products from my API and display them with basic information like title and price. However, the API also provides a l ...

What are the steps to setting up SystemJS with Auth0?

I am having trouble configuring SystemJS for Auth0 (angular2-jwt) and Angular 2.0.0-beta.6 as I keep encountering the following error message: GET http://localhost:3000/angular2/http 404 (Not Found)fetchTextFromURL @ system.src.js:1068(anonymous function) ...

Encountering Syntax Errors during Angular 6 production build

I encountered an issue with my project. Everything was running smoothly, and even when I executed the command ng build --prod, it compiled successfully and generated the dist folder in my project directory. However, after copying this folder to the htdoc ...