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

Encountering npm3 installation errors with typyings in Angular 2?

Each time I try to sudo npm install Angular 2 modules, everything updates and installs correctly. However, I encounter the following error when the typings install is attempted: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0 ...

Having trouble accessing a custom factory within a directive in Angular using TypeScript

Having some trouble with my injected storageService. When trying to access it in the link function using this.storageService, I'm getting an undefined error. Any assistance on this issue would be greatly appreciated. module App.Directive { import ...

How to efficiently retrieve parent content from a child component

parent.html <ion-content class="project"> <ion-grid> <ion-row class="details"> <project [data]="data"></project>// this child component </ion-row> </ion-grid> </ion-content> project.ht ...

Exploring the nuances of checking lists in TypeScript

In the following list: empList = ['one','two','finish','one','three'] I am required to evaluate conditions based on empList: Condition 1: If 'two' appears before 'finish', set this ...

Encountered an error while trying to start the server on port 9876: Permission denied (Error: EACCES) while running Angular Unit Tests using the command 'ng test'

While running my Unit Tests in watch mode, Chrome abruptly closed, preventing me from being able to run 'ng test' anymore. This is a situation that has never happened before during the past year of working on these tests. The issue I encountered ...

Struggling to obtain the Variable

Trying to send a POST request to my ESP8266 HTTP Server, I need to transmit 4 variables: onhour, offhour, onminute, offminute. These variables should be retrieved from a timepicker-component imported from "ng-bootstrap" Despite numerous attempts over the ...

How to update a variable in the app.config.json file in Angular 5

I've created a custom asset JSON configuration file called .angular-cli.json to use as default. However, there are certain instances where I need to update specific values within this file but I'm not sure how to go about it. Any suggestions? .a ...

What is the best way to interpret the property 'subscribe' of an undefined object?

After cloning a MEAN stack application from GitHub, I made minor modifications by changing all instances of the word 'employee' to 'sensor'. The build was successful without any issues. However, upon launching localhost:4200, I encounte ...

Strategies for ensuring that code does not execute in Angular until the API response has been received

Currently, I am facing an issue where I need to wait for data from an API in order to set the value of a variable and use it in an if condition. The problem lies in my uncertainty about how to properly handle this asynchronous task using async and await. ...

What is preventing me from consistently accessing the Type Definition while my cursor is on a JavaScript/TypeScript parameter name in VS Code, and what are some strategies I can use to overcome this issue?

Imagine I have the following code snippet in my VS Code: type T1 = { x: number }; type T2 = { x: number } & { y: string }; function foo(arg1: T1, arg2: T2) {} If I place my cursor on arg1 and go to the type definition (either through the menu or a sh ...

The Nestje subscription is encountering a NULL value and displaying an error message stating: "Non-nullable field Subscription cannot be returned as null."

I attempted to implement a Subscription in my nestjs project with GraphQL, but encountered the following error message: Cannot return null for non-nullable field Subscription Below is the code snippet: //* ~~~~~~~~~~~~~~~~~~~ Subscription ~~~~~~~~~~~ ...

Deprecated: Ngx Progress Bar will no longer be supported due to changes in

In the scenario below, I have noticed that BrowserXhr is outdated: { provide: BrowserXhr, useClass: NgProgressBrowserXhr } But when I refer to the documentation, it directs me to the main HttpClient page without showing an alternate provider example. Wha ...

Obtaining additional information for Observable<Object[]>

I have a scenario where I am working with a service that returns Observable<Object[]>. Each Object in the array has a subObjectId property. My goal is to populate the object's subObject property with data retrieved from another service. How can ...

Is it possible to secure an API endpoint from unauthorized access by external authenticated users not originating from the requesting application?

Currently, I am developing an Angular application where users can log in, track their progress, and earn levels/experience points. The app uses a Node.js/Express API for backend functionality, and I need to implement a way for the app to award experience ...

Tips for customizing the appearance of a label when a MUI Radio Button is selected

Hello everyone, I am attempting to customize the label text color of a radio button to turn blue when selected. https://i.stack.imgur.com/btSc2.jpg HERE IS THE CODE FOR MY MUI BUTTON SO FAR import * as React from "react"; import Radio from &quo ...

What is the best way to adjust the height of a dropdown box in an angular application?

Is there a way to change the height of the scroll view? It seems too long for my liking, any advice? I attempted to adjust it using css but unfortunately, it didn't work out. The scroll view appears excessively lengthy as shown in the image below. ...

Using custom hooks in JSX triggers a TypeScript error when the returned component is accessed

i just created a custom hook // useDropdown.ts function useDropdown(defaultState: number, options: number[]) { const [state, setState] = useState(defaultState); function Dropdown({ name }: { name: string }) { return ( <> <sel ...

Tips for connecting to a docker container containing an Angular application while the Angular app is also running in its own container

I have encountered an issue with my application that consists of a frontend and a backend running together in a Docker compose container. The backend has been functioning well without any problems during development, but the frontend, which is an Angular a ...

Changes in the styles of one component can impact the appearance of other

When it comes to styling my login page, I have specific stylesheets that I include in login.component.ts. For all the common CSS files, I have added them in the root index ("index.html") using the traditional method. However, after a user logs into the sys ...

Angular2's $compile directive functions similarly to AngularJS 1's $compile directive

I am currently in the process of migrating my project from Angular 1 to Angular 2 and I am in need of a compile directive. However, I am struggling to rewrite it to achieve the same functionality as before. app.directive("compile", compile); compile.$inje ...