Angular 7 TypeScript code not updating value

UPDATE: I'm having trouble with my code not updating the selected value with the new one entered in the input field "newVb". The error message says 'this.newVarde' is undefined when it reaches the line 'this.selectedVarde = this.newVarde'. Instead of updating the selected value, it's adding a new one. I'm stuck on why this is happening...

.ts

export class RightMenuComponent implements OnInit {

  public selectedVarde: this.selectedVarde;
  public newVarde: Varde;



  constructor(private _vardeService: VardeService) {
  }

updateVarde() {


    var beskrivning = this.selectedVarde;
    var newVarde = (<HTMLInputElement>document.getElementById('newVb')).value;


   this.varde = {

     Beskrivning: newVarde,
   }


    this.selectedVarde = this.newVarde;
    this._vardeService.updateVarde(this.varde).subscribe(() => { console.log("Lyckat") });


  }

And then my .html:

<label for="updateVarde">T:Värdet som du vill uppdatera</label>
            <select [(ngModel)]="selectedVarde" id="selectedVarde" name="updateVarde" class="form-control" required >
              <option *ngFor="let varde of allaVarden" [ngValue]="varde">{{varde.beskrivning}}</option> 
            </select>
            <button type="button" class="btn btn-primary" (click)="updateVarde()" style="margin-left:4%;" data-toggle="modal" data-target="#vardeModal" data-dismiss="modal">T:Redigera valt värde</button>
            <label for="beskrivning">T:Nytt värde: </label>
            <input class="input" style="width:10%;" id="newVb" type="text">

Appreciative of any insights on what might be causing the issue in the code

Answer №1

You are correct, the value is undefined because it has not been set.

These are the properties/variables defined in your component:

public selectedVarde: Varde;
public newVarde: Varde;
public beskrivning: Varde;

In the method, you then declared and initialized new scoped variables with the same name as follows:

var beskrivning = this.selectedVarde;
var newVarde = (<HTMLInputElement>document.getElementById('newVb')).value;

this.varde = {
 Beskrivning: newVarde,
}

This is why this.newVarde remains undefined at this point.

this.beskrivning = this.newVarde;

Edit:

Instead of creating a new variable, consider using the ones already defined:

this.beskrivning = this.selectedVarde;
this.newVarde = (<HTMLInputElement>document.getElementById('newVb')).value;

this.varde = {
 Beskrivning: this.newVarde,
}

Edit 2:

Since the newVarde in your method updateVarde does not refer to the newVarde in your component, you need to declare and initialize it within the method:

this.beskrivning = this.selectedVarde;
const newVarde = (<HTMLInputElement>document.getElementById('newVb')).value;

this.varde = {
 Beskrivning: newVarde,
}

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

Display a loading indicator when loading a lazy loaded module in Angular 2

Here's my situation: I have a menu with various options that should be displayed based on user permissions. The majority of the menu items are contained within modules, and these modules are lazy loaded. This means that when a user clicks on a menu it ...

What is the process for running an Angular 1.4 application on a system with Angular 6 installed?

After installing Angular 6 with CLI, I realized that my project was written in Angular 1.4. How do I go about running it? ...

Recently updated from Angular 9 to 14 and noticed a peculiar issue in the deployed app - all API calls seem to only reference the root or hosted URL in the request URL

After upgrading the application from angular 9 to angular 14, I encountered a network call issue. The application was successfully deployed via azure devops, but all network calls were directed to the host URL instead of the expected API endpoints. For exa ...

Guide on inputting Vue component in props

<template> <v-dialog width="auto" v-model="isShown" transition="dialog-bottom-transition" > <v-card> <v-card-title v-if="title"> {{ title }}</v-card-title> ...

Leverage elements from nearby npm repository when building an Angular 2 application

After developing a generic chart component using d3 and Angular 2, I decided to share it by publishing it in a local npm repository. This way, anyone can easily incorporate the chart component into their Angular project by simply running the npm install my ...

Changing Observable to Promise in Angular 2

Q) What is the best way to convert an observable into a promise for easy handling with .then(...)? The code snippet below showcases my current method that I am looking to transform into a promise: this._APIService.getAssetTypes().subscribe( assetty ...

How to prevent the 'page' output event from triggering when scrolling in ngx-datatable?

My preference is to avoid infinite scroll pagination; instead, I only want pagination to be triggered by clicking the page numbers in the footer. Since I am using server-side pagination, constantly triggering the 'page' event with every scroll ca ...

Challenges encountered when passing objects with Angular 2 promises

I am encountering a problem when using a promise to retrieve a Degree object in Angular 2. The initial return statement (not commented out) in degree.service functions correctly when paired with the uncommented implementation of getDegree() in build.compon ...

Oops! There seems to be an issue with Angular - I'm getting an

I need to retrieve JSON data from the server and only display it on the web page after clicking a button. However, I encounter an error after the first click: core.js:4352 ERROR TypeError: Cannot read property 'imie' of undefined at HttpTestC ...

The tooltip is being truncated

https://i.sstatic.net/o41Qz.png Struggling with a tooltip that keeps getting cut off? I've tried everything and still can't get it right. <th class="fd-table--header-cell" scope="col"> <p class=&q ...

Whenever I attempt to run my application using ng serve on Linux, I encounter the error stating: "Module '@angular-devkit/build-angular/package.json' cannot be found."

Hey everyone! I'm facing an error when trying to run my app from the terminal on Linux. The command I used was: ng serve And the error message I received in the terminal is as follows: AppBlog/blog# ng serve An unhandled exception occurred: Cann ...

How to modify the port for the inspector in ng serve configuration?

Whenever I try to run ng serve server in the command line, it fails with the following message: Starting inspector on localhost:7777 failed: address already in use It is expected since there is already another instance running. So, how can I change the ...

Guide on how to connect several Subjects within an object literal to their corresponding Observables in another object literal

I am currently developing a class using Angular and I need to share multiple states associated with that class. To accomplish this, I have created several instances of BehaviorSubject private subjects = { a : new BehaviorSubject<A>(this.a), b ...

The solution to resolving setState not updating within a react context

I am encountering a problem where my context does not seem to update when I attempt to modify it using a react hook. The code snippet is provided below, and I have a feeling that I might be overlooking something minor. appContext.tsx import React, { use ...

Using Typescript: invoking static functions within a constructor

This is an illustration of my class containing the relevant methods. class Example { constructor(info) { // calling validateInfo(info) } static validateInfo(info):void { // validation of info } I aim to invoke validateInfo ...

Looking to retrieve the smallest amount of array sets in Angular4

I'm currently developing an Angular 4 application and facing an issue with a function I'm trying to write. The goal is to extract the minimum and maximum numbers from three array objects. The yAxisData object consists of three yaxis array objects ...

Generate a configuration file that allows for the reading and storage of modifications

Is there a way to create a configuration file (JSON) on the local file system using JavaScript where I can write and modify data without losing it when the application is restarted? Any suggestions or solutions for this problem? Thank you for your assista ...

Changing return values with Jest mocks in TypeScript

Here I am again with a very straightforward example. In summary, I require a different response from the mocked class. Below is my basic class that returns an object: class Producer { hello() { return { ...

Bring in properties from a separate file in Vue3

Currently, I am utilizing Vue3 along with the options API. Within my setup, there are various Vue components that rely on a shared prop defined as: exercise: { type: Object as PropType<Exercise>, required: true, }, To streamline this pro ...

What is the best way to generate a random item when a button is clicked?

I'm currently working on a feature in my component that generates a random item each time I access the designated page. While the functionality is set to automatically refresh and showcase a new random item, I am now looking to trigger this action man ...