Unable to assign the initial value of the array to the object's value, encountering an issue

I have a selection box in HTML where users can select options. I've figured out how to store the selected items (in this case, the course ID) in an array called courseDataSend, such as ['1'] or ['1','2']. I can use console.log() to display it.

Now, I need to create an object named sendCourse with a property called id_course that should take the values from the courseDataSend array. I tried to achieve this using the following code:

reg()
  {
    for(let i=0; i<this.courseDataToSend.length; i++)
    {
      console.log(this.courseDataToSend[i])   // It displays '1' or '1' and then '2' when options are selected
      this.sendCourse.id_course=this.courseDataToSend[i]
    }
  }

The reg() function is triggered upon clicking the submit button. However, an error message appears in the console stating:

TypeError: Cannot set property 'id_course' of undefined

I included the For loop because I want to create the object once, send it to the server, replace it with new data if another option is selected, and then resend it to the server.

I'm not sure what to do next.

file: register.component.ts

  coursesData : any = {}
  courseDataToSend : Array<string> = []
  sendCourse : {
    'id_user': any,
    'id_course': any,
  }

  constructor(
    private _auth: AuthService,
    private _courseService: CourseService,
    private _router: Router,
    private _flashMessage: FlashMessagesService) { }


  ngOnInit() {
    this._courseService.getCourses()
      .subscribe(
        res => 
        {
          this.coursesData= res['courses'];
          console.log(this.coursesData)
        }
      )
  }

  reg()
  {
    for(let i=0; i<this.courseDataToSend.length; i++)
    {
      console.log(this.courseDataToSend[i])   // It shows '1' or '1' and then '2' when options selected
      this.sendCourse.id_course=this.courseDataToSend[i]
    }
  }

file: register.component.html:

   <div class="form-group">
        <label for="registerCourses">Select your courses (additional):</label>
        <select [(ngModel)]="courseDataToSend" name="courses" multiple class="form-control"
            id="exampleFormControlSelect2">
            <option *ngFor="let course of coursesData" [value]="course.id">{{course.name}}</option>
        </select>
        <small id="interestsHelp" class="form-text text-muted">To select more than one item: hold down the control button and click</small>
    </div>

        <div class="text-right">
            <button (click)="reg()" type="submit" class="btn btn-primary"
                style="margin: 15px;">Register</button>
        </div>

Answer №1

To update the sendCourse variable, simply modify the declaration like this:

sendCourse : any = {
    'user_id': '',
    'course_id': ''
  }

Answer №2

The problem arises from attempting to assign a value to an object before the variable is defined. To resolve this issue, you can either set the entire object like this:

for(let i=0; i<this.courseDataToSend.length; i++)
{
  console.log(this.courseDataToSend[i])   // It displays '1' or '1' and then '2' when options are selected
  this.sendCourse = { id_course: this.courseDataToSend[i], id_user: undefined }
}

Alternatively, you can initialize your sendCourse object at minimum like this:

  sendCourse : {
    'id_user': any,
    'id_course': any,
  } = { id_user: undefined, id_course: undefined }

Here is a working example on Stackblitz that demonstrates how undefined and null values propagate and can be managed in each scenario:

https://stackblitz.com/edit/angular-ivy-mkesxe?file=src%2Fapp%2Fapp.component.ts

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 functionality does the --use-npm flag serve in the create-next-app command?

When starting a new NextJS project using the CLI, there's an option to use --use-npm when running the command npx create-next-app. If you run the command without any arguments (in interactive mode), this choice isn't provided. In the documentati ...

What is the type of return from withRouter?

I'm a beginner with TypeScript and React. I'm encountering an error with Eslint that says "Missing return type on function" in my React HOC that uses withRouter. I'm puzzled about how to define the return type for the filterRedirectHOC funct ...

Angular chat integration

In my application, I have a parent component called "chat" with two child components - "sidebar" (which displays the user list) and "conversation detail" (which shows the chat with each user). The functionality I am aiming for is that when a user is clicke ...

The scrolling on the image listing webpage is not as fluid as desired

I'm currently working on building a website for displaying images in Angular, similar to Google Photos. The site includes a custom scrollbar that displays the month and year. I want the image list to scroll when the user moves the scrollbar thumb. Her ...

Building with Angular seems to be dragging on forever

Working with Angular 6.7 on a finance application that consists of over 80 modules. When I run the build using the command: node --max_old_space_size=16384 ./node_modules/@angular/cli/bin/ng build --prod The build process takes more than 90 minutes to com ...

Angular Dom does not update when invoking a function within a separate component

Greetings everyone! I am facing a situation where one component (let's name it recipe component) has a reference to another component (named grocery component). The method in my recipe component uses the reference to the grocery component to call a s ...

Pipe for Angular that allows for searching full sentences regardless of the order of the words

I am looking to create a search bar that can search for the 'title' from the table below, regardless of the word order in the sentence. I attempted to use a filter pipe to check if the search string exists in the title. I also experimented with ...

Having trouble loading image on web application

Currently, I am facing an issue while attempting to add a background image to an element within my Angular web application. Strangely enough, the relative path leading to the image seems to be causing my entire app to break. https://i.stack.imgur.com/b9qJ ...

Encountering issues with `Partial<this['someProperty']>` usage in TypeScript

Provided class A { props: { bool?: boolean, test: string } = { test: 'a' }; setProps(newPropertiesr: Partial<this['props']>) { } a() { this.setProps({ bool: fals ...

How can I make the snackbar open multiple times in a row?

Check out this codesandbox I created to show an issue. When you click the button, a MUI snackbar opens. However, if you close it and try to reopen it, nothing happens. Do you think the problem is related to how I'm using hooks? Explore the sandbox h ...

After upgrading Expo, the React Native Auth Session ceased to function

During my use of Expo SDK 48, my app successfully implemented Google and Facebook authentication with a web browser-based authentication method. Functional code: type AuthResponse = AuthSession.AuthSessionResult & { params: { access_token ...

Leveraging WebWorkers in Typescript alongside Webpack and worker-loader without the need for custom loader strings

I've been trying to implement web workers with Typescript and Webpack's worker-loader smoothly. The documentation shows an example of achieving this using a custom module declaration, but it requires the webpack syntax worker-loader!./myWorker. ...

Defining a TypeScript structure for a JSON object by referencing another entry within the same object

I'm currently working on defining a TypeScript structure for a JSON object. One part of the object includes a property called components, which is an array of strings. However, I want to enhance this structure by adding an additional property called o ...

Modifying iframe src using click event from a separate component in Angular 10

I am looking to dynamically update the src attribute of an iframe when the menu bar is clicked. The menu bar resides in a separate component and includes a dropdown menu for changing languages. Depending on which language is selected, I want to update the ...

How to create a TypeScript generic function that takes a key of an object as a type argument and returns the corresponding value of that key in the object

My system includes various object types: type Slave = { myKey:string } type AnotherSlave = { anotherKey:string } In addition, there is a master type that contains some keys, with the object types mentioned above as the values for those keys: type Mas ...

Can the output type of a function be dynamically determined by using the function parameter name as the property in an interface?

I am attempting to dynamically assign the output of a function based on the name of the input parameter within an existing interface: interface MyInterface { typeA: string; typeB: boolean; typeC: string; typeD: number; ... } const myFunction: ( ...

Angular 2- Unable to bind to 'ngSwitchCase' as it is not recognized as a native property

I am facing an issue with my code where I have two lists that are displayed in my .html file. In order to avoid repetition, I decided to utilize ngSwitch. However, when I try to implement this approach, I encounter an error. Here is the snippet of code cau ...

Concise way to add or insert an element into an array, at a specific property of an object

I am working with an object of the ObjectOfArrays type: type ObjectOfArrays = { [id: string]: Array<string> }; Throughout my code, I need to add strings to the correct array based on the id. Currently, I am using the following approach: if (id i ...

Encountering a problem with ng serve while attempting to launch the project

I am completely new to Angular and recently installed the latest version of Node.js along with Angular CLI globally. I cloned a project from GitHub and attempted to run it using 'ng serve', but encountered an error message: https://i.sstatic.net ...

The angular-cli has encountered a glitch and cannot be reinstalled due to an issue with the @angular/compiler-cli version. To proceed, the version must be updated to 2.3.1 or higher,

npm remove global angular-cli npm remove --save-dev angular-cli Next, clear the cache and install the updated version npm clean cache npm install --save -g <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dabbb4bdafb6bba8f7b9b6 ...