TypeScript setter failing to activate

Here is a snippet of code from a class called VibrationElement:

export class VibrationElement {

    private _amplitude: number;

    get amplitude(): number {
        return this._amplitude;
    }

    set amplitude(amplitude: number) {
        console.log("test");
        if (this.validate(amplitude)) {
            this._amplitude = amplitude;
        }
    }

}

In my component, I have a method to change the amplitude of an instance of VibrationElement:

export class VibrationPatternEditingComponent {
    
    ...

    amplitudeChange(vibration: VibrationElement, newValue: any) {
        vibration.amplitude = parseInt(newValue);
    }

}

The issue I am facing is that the setter of VibrationElement is not being called (no "test" in console) when I try to update the value. However, the value does change without triggering the setter. It's important for me to validate constraints on the amplitude, so the setter is necessary.

I also attempted using

Object.assign(vibration, {amplitude: parseInt(newValue)});
, but that too failed to trigger the setter.

Interestingly, when I use

[(ngModel)]="vibration.amplitude"
within an input form, the setter is triggered. The downside is that the input ends up being a string. This presents a problem when converting it to a number inside the setter since it receives a number parameter, yet somehow it registers as a string when I log typeof amplitude inside the setter. I'm confused by this behavior and would appreciate any insights or solutions anyone might have.

Answer №1

You have the ability to convert or cast a string into a number by implementing the following approach:

export class VibrationElement {
    
    private _amplitude: number;

    get amplitude(): number {
        return this._amplitude;
    }

    set amplitude(_amplitude) {
        const amplitude = Number(_amplitude);
        console.log("test");
        if (this.validate(amplitude)) {
            this._amplitude = amplitude;
        }
    }

}

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 a situation where d3.events is returning null within Angular 2 TypeScript code

Seeking to enhance my d3 maps with tooltips, I came across a helpful code snippet at this link However, upon implementing the same code in an Angular 2 TypeScript file, an error emerged: Error: Cannot read property 'transition' of undefined Th ...

Is it possible to integrate @google-cloud/logging into an Ionic4/Angular8/Firebase client application? Tips for resolving module import issues

I am trying to implement nodejs-logging in my app using Ionic 4, Angular 8, and Firebase for writing logs to StackDriver. In the root of my app, I have taken the following steps: Installed @google-cloud/logging using npm Navigated to @google-cloud/loggi ...

Incorporate a 'Select All' functionality into ion-select by adding a dedicated button

Looking for a way to set custom buttons on ion-select through interfaceOptions in ionic 4? HTML <ion-item> <ion-label>Lines</ion-label> <ion-select multiple="true" [(ngModel)]="SelectedLines" [interfaceOptions]="customAlertOption ...

Executing an Angular2 Function in Unity WebGL

Currently, I am utilizing Angular2 version 2.1.2 along with a Unity visualizer created with Unity 5.5. My main requirement is to establish communication from Unity to Angular2. I had previously used a code snippet similar to the one below public void G ...

Different TypeScript parameters that cannot be used together

Consider the given JavaScript function below: function x({foo, fooId, bar, barId}) {} I am looking to refactor this function into TypeScript in such a way that the caller is required to provide either foo or fooId, but not both. The same rule should apply ...

Can Javascript (PWA) be used to detect fake GPS or mock GPS in applications?

Looking for a solution to prevent users from using Fake Location tools in my PWA application that gathers absence location data. Is there a method or package in JavaScript to detect the presence of Fake GPS installed on the device? ...

The visual representation remains unchanged even after updating the model

I'm currently tackling an issue with my football project, specifically when updating a service model. The project involves two key components - AvailablePlayers and SelectedPlayers, as well as two corresponding services - AvailablePlayersService and S ...

Compatibility of Ng-bootstrap with Angular 9

Ever since the upgrade to Angular 9, I've been encountering a series of errors related to ng-bootstrap: ERROR in src/app/shared/Components/form-controls/dropdown-select/dropdown-select.component.ts:87:63 - error TS2304: Cannot find name 'NgbDrop ...

Step-by-step guide for inputting a sophisticated formula in exceljs using JavaScript

Currently, I am working on a project that involves exporting data into multiple xlsx sheets. One of the sheets requires me to add a formula in cells that meet certain conditions before adding data from the first sheet. Here is an example: Ref !== null ? wo ...

How to build a personalized dialog box with CdkDialogContainer

Currently, I am in the process of developing an Angular service (version 14.2.0) to implement a Tailwind/Flowbite dialog (which is known as a modal in Flowbite terminology). It appears that in order to ensure the proper DOM structure and class application ...

Utilizing Sentiment Analysis API with Ionic 2 Angular and handling CORS restrictions

Currently, I am in the process of developing a mobile application that can analyze an individual's thoughts using the Aylien Sentiment Analysis API. The technology stack I am utilizing includes Ionic 2 and Angular 4. While I have successfully integrat ...

Having trouble with installing Bootstrap in Angular 5

My journey with Bootstrap began by executing the command below: npm install --save bootstrap The installation was a success, and I proceeded to incorporate the CSS as follows: "styles": [ "../node_modules/bootstrap/dist/css/bootstrap.min.css", ...

Can you tell me what that sequence of characters is at the conclusion of a styled-component?

Technology Stack: React, Typescript I believe this question may have been asked before, but I am unsure how to search for it... I am interested in creating a wrapper for the styled-components library... Here is the API reference for the specific packag ...

Utilizing React Bootstrap with TypeScript for Styling Active NavItem with Inline CSS

Is it possible to change the background color of the active NavItem element to green using inline CSS in React Bootstrap and React Router Dom? I am currently using TypeScript 2.2 and React. If not, should I create a CSS class instead? Here is the code sni ...

Exploring the dynamic duo of SystemJS and AngularJS 2

I am currently working on integrating the Core Angular2 module into my application, which is written in Typescript. It's essentially following the same structure as the quick start tutorial on the Angular.IO website. However, I am facing a challenge ...

Instructions on configuring the chart data in an Angular application sourced from a backend Node.js API connected to a MongoDB database and displayed on an HTML page

app.component.html This particular file is where I showcase my chart <div style="display: block;"> <canvas baseChart width="400" height="400" [datasets]="lineChartData" ...

Configuring environment variables during Jest execution

A variable is defined in my `main.ts` file like this: const mockMode = process.env.MOCK_MODE; When I create a test and set the variable to true, it doesn't reflect as `'true'` in the main file, but as `'false'` instead. describe ...

Learn how to utilize the "is" status in Postma within your code, even when this particular status is not included in the response

Service.ts Upon invoking this function, I receive a JSON response similar to the following: public signupuser(user: Users): Observable<boolean> { let headers = new Headers(); headers.append('Content-Type', 'application/json&a ...

Implementing reduce for filtering and mapping in TypeScript: A comprehensive guide

I encountered a problem with my code that I need help fixing. Here is a simple example: interface employer { name: string; age: number; } const arr: employer[] = [{name:'Amy',age:18},{name:'Bob',age:20}]; l ...

Trigger the identical event to be sent to two distinct functions upon the corresponding button click in Angular 2 using Typescript

I recently implemented a service that fetches JSON data and subscribes to two different variables within my component. These variables are then used by two separate drop-down lists to filter the data accordingly. The filtered data is then sent to another s ...