The object is given a value in the form of a string, even though it is a strongly-typed variable

I'm encountering something unusual in my code. In the following example, there is a (change) event that captures the current value selected by the user from a dropdown menu.

<div style="padding-right: 0; width: 100%;">
    <label style="width: 100%;">
      <select
        [(ngModel)]="courseContentButtonSelectedEvent"
        class="course-content-sidebar-form-control"
        (change)="setCourseContentButtonEventStep($event)"
      >
        <option
          *ngFor="let courseContentButtonEvent of courseContentButtonEventList"
          [value]="courseContentButtonEvent.id"
          [selected]="courseContentButtonEvent.id == courseContentButtonSelectedEvent"
          >{{ courseContentButtonEvent.value }}</option
        >
      </select>
    </label>
  </div>

The mentioned method is setCourseContentButtonEventStep.

  setCourseContentButtonEventStep(event: Event): void {
    const courseContentButtonEventType: CourseContentButtonEventType = ((event.target as HTMLInputElement)
      .value as unknown) as CourseContentButtonEventType;
    let courseContent = JSON.parse(JSON.stringify(this.courseContent));
    this.courseContent = CourseContentService.setCourseContentButtonEventStep(
      courseContent,
      courseContentButtonEventType,
      this.selectedCourseContentUid,
      this.selectedCourseElementUid,
      this.courseContentButtonEventIndex
    );
    this.store.dispatch(builderActions.setCourseContent({ courseContent: courseContent }));
  }

This method then invokes the setCourseContentButtonEventStep function within the CourseContentService.

  static setCourseContentButtonEventStep(
    courseContent: ICourseContent[],
    courseContentButtonEventType: CourseContentButtonEventType,
    selectedCourseContentUid: string,
    selectedCourseElementUid: string,
    courseContentButtonEventIndex: number
  ): ICourseContent[] {
    for (let i = 0; i < courseContent.length; i++) {
      if (courseContent[i].uid === selectedCourseContentUid) {
        for (let j = 0; j < courseContent[i].button.length; j++) {
          if (courseContent[i].button[j].uid === selectedCourseElementUid) {
            for (let k = 0; k < courseContent[i].button[j].event.length; k++) {
              if (k == courseContentButtonEventIndex) {
                courseContent[i].button[j].event[k].action = courseContentButtonEventType;
              }
            }
          }
        }
      }
    }
    return courseContent;
  }

Now interestingly, despite the casting of courseContentButtonEventType, it is being added to the object as a string instead of a number. For instance, inspect the data object below, under button -> event -> action, specifically

"action": "4"
:

[
  {
    "id": 1,
    "uid": "card-HJUI9b9Nre",
    "body": {
      "text": "Testing"
    },
    "type": 0,
    "button": [
      {
        "uid": "button-4WhgDe8mhe",
        "title": "Get Started",
        "event": [
          {
            "id": 1,
            "action": 5,
            "value": "https://en.wikipedia.org/wiki/Educational_technology"
          },
          {
            "id": 2,
            "action": "4"
          }
        ],
        "isEnabled": true
      }
    ],
    "audio": {
      "uid": "audio-NIiH1fCkqd",
      "url": "https://s3.eu-west-2.amazonaws.com/media.example.co.uk/default/testing_startup_ideas.mp3"
    }
  }
]

Answer №1

If you want to tidy up your code, consider using ngValue instead of value.

<select
[(ngModel)]="courseContentButtonSelectedEvent"
class="course-content-sidebar-form-control"
(ngModelChange)="setCourseContentButtonEventStep($event)"
>
    <option
      *ngFor="let courseContentButtonEvent of courseContentButtonEventList"
      [ngValue]="courseContentButtonEvent"
      [selected]="courseContentButtonEvent.id == courseContentButtonSelectedEvent"
      >{{ courseContentButtonEvent.value }}</option
    >
</select>

By using ngValue instead of value, you can store an object instead of a string.

Also, pay attention to the difference between (change) and (ngModelChange).

setCourseContentButtonEventStep(courseContentButtonEventType: CourseContentButtonEventType): void {
    let courseContent = JSON.parse(JSON.stringify(this.courseContent));
    this.courseContent = CourseContentService.setCourseContentButtonEventStep(
      courseContent,
      courseContentButtonEventType,
      this.selectedCourseContentUid,
      this.selectedCourseElementUid,
      this.courseContentButtonEventIndex
    );
    this.store.dispatch(builderActions.setCourseContent({ courseContent: courseContent }));
}

This refactoring will greatly improve the readability of your event handling logic.

One more thing to note is the type in your event handler, "CourseContentButtonEventType". Is this intentional? Does it match the items in your list?

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

Unable to refresh JSON data in Datatables

Ensuring this operation is simple, I am following the documentation. An ajax call returns a dataset in JSON format. The table is cleared successfully, but even though data is returned according to the console statement, the table remains empty after the su ...

Redirecting to new page after submitting form using Ajax

I'm having some trouble with my HTML form submission using JQuery and AJAX. After successfully submitting the form, I want to display a modal and then redirect to another page based on certain conditions. I've written the logic in my JS file wh ...

Tips for expanding a fabric canvas to match the entire width of its parent division

specific scenario I have a cloth canvas placed inside a main section. How can I expand the canvas to cover the entire width and height of its container? Here is what my current code looks like: <div class="design_editor_div"> &l ...

Picture in the form of a radio button

Is there a way to use an image instead of a radio button in my AngularJS form? I have managed to hide the radio button using CSS, but it disables the checked event. How can I make the image clickable? position: absolute; left: -9999px; Here is the code s ...

A guide on navigating through nested JSON objects with the help of async.js

Having recently transitioned from a Python background to nodeJS/Javascript's asynchronous nature, I am exploring how to traverse a nested JSON object and extract its values using async.js. In my quest for answers, I stumbled upon this helpful snippet ...

Tips for including multiple JSON results into a single text box for auto-complete purposes

I am trying to combine different autocomplete list results into one text box. It's straightforward to use separate text boxes for different autocomplete results. HTML: <input id="university" name="university" type="text" /> <input id="unive ...

how to use jQuery to locate the immediately preceding node that meets specific criteria

How can I locate the nearest parent node above $(this) node that has a specific property such as class="field", without considering parent/child relationships? ...

Modifying multiple objects with Vue's V-Model

When utilizing the mounted function in Vue to assign two different objects in the data area and bind one of them to a form, an unusual issue arises: Both objects change when input values are entered in the form For example: <template> <v-card ...

The continual appearance of "No file found" persists when utilizing the $redirectRoute

My goal is to make one of the links on my website lead to another page within the site. Below is one of the two links found on my index.html page: <html ng-app="myApp"> . . . <body> <h1>My Home Page</h1> ...

A Unique Identifier in Kotlin

In my typescript class, I have a member that accepts any as the name: interface ControlTagType { type?: String | null; [name: string]: any } class ControlTag { tagSource: String | null = null; tag: ControlTagType | null = null; } expor ...

jQuery script unable to alter img src in Firefox and IE browsers

I am working with an image and a jQuery script to change the captcha image. <img src="captcha.jpg" id="my-image"/> The jQuery script is as follows: <script> $(document).ready($("#my-image").click(function(){ $('#my-image&ap ...

Deliver a numerical input to the component on an equivalent hierarchical tier

I need to find a way to pass the values of the "things" array to another component on the same level in my app. The structure of my app is as follows: sidebar.component data.service body.component In the sidebar component, I have a button that triggers a ...

Tips for creating dynamic alerts using mui v5 Snackbar

My goal is to call an API and perform several actions. After each action, I want to display the response in a Snackbar or alert. Despite iterating through the messages in a map, I'm only able to show the first response and none of the others. Here is ...

What is the best way to access nested objects in React Native?

Here is the JSON data I am working with: [ { id: 51, name: 'Boat Neck Blouse', image: { id: 669, date_created: '2018-08-27T10:05:39', date_created_gmt: '2018-08-27T10:05:39', date_modified ...

Submitting information to an HTML page for processing with a JavaScript function

I am currently working on an HTML page that includes a method operating at set intervals. window.setInterval(updateMake, 2000); function updateMake() { console.log(a); console.log(b); } The variables a and b are global variables on the HTML page. ...

Looking for assistance with getting 2 functions to run onLoad using Ajax - currently only 1 is operational

In the coding journey, I first implemented shuffle functions for arrays which was successful. Then, I proceeded to define two global variables that would dictate the random order in which images are displayed on the webpage. The variable picOrder was meant ...

Once an ajax request is made, scripts cease to function correctly

There is a dynamic table on a webpage that I update using ajax. The table contains checkboxes and there are scripts that utilize the checkboxes for certain functionalities, such as toggling the check/uncheck status of all checkboxes when a "Check all / Unc ...

Retrieve a specific element from an array list

Hey everyone, I'm facing a problem in my application where I need to extract a specific value from my array and display it in a table for users to see. Check out the code snippet below: Here's my mock data: { "Data": "2020-0 ...

Encountering an unexpected token ';' in a random generator while attempting to utilize an if-else statement for determining DOM manipulation

After dabbling in programming on and off for a few years, I've finally decided to dive deep with some simple personal projects. One of the tasks I'm working on is creating a randomizer for a pen and paper RPG, where it samples from an array at ra ...

Implementing a codeigniter delete confirmation box with Javascript

I have tried numerous solutions on this site, but nothing seems to be working for me. I am trying to implement a pop-up window confirmation before deleting my data. Here is the code I am using: <a href="<?php echo site_url('admin/barang/delet ...