Is it possible to utilize a component's property as an argument for a method in Angular 6?

Within my Angular 6 application, I have a method designed to alter a property of my component. The scenario is as follows:

...
value: number = 10;
changeValue(v) { return v = 100; }
...

Upon invoking this method with the component's property:

this.changeValue(this.value); // the value remains unchanged

I anticipate that this.value should now be 100, but it stubbornly remains at 10. While I am able to access the value of the v parameter (which corresponds to this.value in this case), any attempts to modify it within the function are unsuccessful.

Where exactly am I going wrong and how can I achieve the desired functionality? Would you kindly provide guidance on addressing this issue? Any assistance would be greatly appreciated.

Answer №1

In Typescript, primitives like strings, numbers, and booleans are passed by value. This means that you can take certain actions to work with them.

One option is to assign the result of a method to a variable called value:

changeValue(){
   return 100;
}

this.value = this.changeValue();

Alternatively, you can directly change the value within the method itself:

changeValue(){
   this.value = 100;
}

this.changeValue();

LATEST UPDATE

In response to a comment from Jeto, it was noted that even when passing an object as an argument instead of a primitive, the outcome remains the same because you are modifying the object itself rather than its properties.

value = {foo: 'bar'}

changeValue(v){
    return v = {foo: 'baz'};
}

console.log(this.value); // {foo: 'bar'}
this.changeValue(this.value);
console.log(this.value); // {foo: 'bar'}  #No Change

However, if your goal is to alter a specific property of an object, you can achieve this by changing the property value:

value = {foo: 'bar'}

changeValue(v){
    v.foo = 'baz'
}

console.log(this.value); // {foo: 'bar'}
this.changeValue(this.value);
console.log(this.value); // {foo: 'baz'}  #Modified

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

Whenever the [required] tag switches from being true to false, it generates an event

Initially, I have set up an Angular form using the following code snippet buildForm() { this.form = this.formBuilder.group({ value1: this.formBuilder.control(null), value2: this.formBuilder.control(false) }); } The HTML contains a ...

What steps can I take to address the problem in iOS 17 where sound is coming from the earpiece instead of the speaker during camera activation?

I have a Progressive Web App where I use the getUserMedia() API to access the camera and HTML audio tags for handling media content. However, ever since updating to iOS 17, I've faced an issue where audio plays through the earpiece instead of the medi ...

Using ES6, one can filter an array of objects based on another array of values

Seeking assistance with creating a function to filter an array of objects using another array as reference values. For example: The array containing objects: const persons = [ { personId: 1, name: 'Patrick', lastName: 'Smit ...

Incorporating XMLHttpRequest in my React Typescript App to trigger a Mailchimp API call, allowing users to easily sign up for the newsletter

My website needs to integrate Mailchimp's API in order for users to subscribe to a newsletter by entering their email into a field. I am looking to implement this without relying on any external libraries. To test out the functionality, I have set up ...

Can a new record be created by adding keys and values to an existing record type while also changing the key names?

If I have the following state type, type State = { currentPartnerId: number; currentTime: string; }; I am looking to create a new type with keys like getCurrentPartnerId and values that are functions returning the corresponding key's value in Sta ...

TypeScript is unable to recognize files with the extension *.vue

Can someone assist me with an issue I'm facing in Vue where it's not detecting my Single File Components? Error message: ERROR in ./src/App.vue (./node_modules/ts-loader!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/Ap ...

Leveraging event listeners in conjunction with React's useEffect function

Check out the code example on Code Sandbox here Hey there, I'm trying to implement a feature where clicking a button inside a container displays a box. I've set up an event listener so that when you move your mouse outside the container, the box ...

Issue with ngSubmit not triggering in child component that employs ControlValueAccessor while utilizing [formGroup]

After encountering a situation where ngSubmit was not triggering inside a child component when using [formGroup], but worked fine with formGroupName, I am curious to understand why there is a difference between the two approaches. I have provided examples ...

Tips for creating a versatile function in TypeScript that accepts either a single value or an array of values for two parameters

I'm currently working on a task to develop a versatile function that accepts a parameter called hashMapName, another parameter called 'keys' which can be either a string or an array of strings, and a callback function that will return either ...

Create a TypeScript view component that encapsulates an HTMLElement for seamless integration with TweenMax

Looking to develop my own basic view component class that encompasses an HTMLElement or JQuery element, I want to be able to do something similar to this: var newComponent:CustomComponent = new CustomComponent($('#someDiv')); TweenMax.to(newCom ...

Having trouble correctly inputting the HOC function that accepts a custom property key

Here is a demonstration of an HOC function that takes a component and a property key, injecting a value at the specified property key: import * as React from 'react' type WrappedComponentProps<PropertyKey extends string> = { [k in Proper ...

Typescript combineReducers with no overload

There seems to be an issue with my reducers, specifically with the combineReducers function. While it may be something obvious that I am missing, I keep encountering an error. export default combineReducers<ConfigCategoryState>({ tree: treeReducer( ...

Ways to implement debounce in handling onChange events for input fields in React

I've been attempting to implement debounce functionality in my React app without relying on external libraries like lodash or third-party node modules. I've tried various solutions found online, but none have worked for me. Essentially, in the h ...

Is there a way to execute Angular code synchronously similar to how it is done in C#?

Trying to replicate a C# application in Angular is proving to be challenging for me, particularly when it comes to ensuring that the code runs synchronously. Consider the following example: private void doChecks() { if (isInvoiced()) return; ...

Clicking the button will trigger the onclick event

I'm working on a button component in TypeScript and I have encountered an issue with passing the event to the submitButton function. import * as React from 'react'; interface Props { className?: string; text: string; onClick?(event: Reac ...

Unable to choose Typescript as a programming language on the VSCode platform

Recently, I encountered an issue while using Visual Studio Code with TypeScript. Even though TypeScript is installed globally, it is not showing up in the list of file languages for syntax highlighting. Despite trying various troubleshooting methods such a ...

Tips for maintaining an open ng-multiselect-dropdown at all times

https://www.npmjs.com/package/ng-multiselect-dropdown I have integrated the ng multiselect dropdown in my Angular project and I am facing an issue where I want to keep it always open. I attempted using the defaultOpen option but it closes automatically. ...

Spring MVC seems to be ignoring the static resources specified in the HTML files

Currently, I am in the process of creating a straightforward Spring MVC (v4.1.2) and Angular4 application. Essentially, this application performs CRUD operations by sending HTTP requests from the Angular client. The following combination works seamlessly ...

Tips on displaying the entire text when hovering over it

I'm facing an issue with a select element that retrieves options from an API. The problem is that some options are too large for the text box and get cut off, making them hard to read for users. <div class="form-group my-4"> <lab ...

Trouble with displaying class object array in Angular 5 using ngFor loop

I am attempting to loop through an array of class objects to populate a dropdown menu in Angular 5. However, the dropdown menu is not showing any options and there are no errors appearing in the browser console. The object array is created based on this m ...