Angular 7/6 | Not Reflecting Change in Variable and Model Value Passed in Component Method as Parameter/ Argument Resolved!

In an Angular application in some situations, we need to make changes in local variables which are getting used and defined as global. These variable or Model values does not reflect any change if we pass them as argument or parameter in a component method, then change in that parameter value does not reflect globally in view.

As these become local to that method and does not act as a pointer to that global variable.

Let’s understand this with an application having two versions:

First version: This is not working as expected, Here we defined a boolean variable in App component isWorking set to false value.

Now, let’s show this value in view and a click event calling a method to change its value from false to true. But you will realize this value is not changing.

In this case, the only option left is to change of global variable instead of a local variable in the method. We can do that as follows:

 

This will work as expected, but in some situations, we want to modularize a single variable to use multiple places, then this will not help.

How to Resolve this?

We can resolve this situation by simply using DOT(.) operator. Yes! we only need to use the dot for variables and models we are using in the application. So take a look at changes we need to do.

Second version: In Component, we will define a variable “data” of type any. Then add isWorking as part of it. In method also we will take data as a parameter then take isWorking out of it to change its value.

In view, we will pass data as the parameter.

So here we discussed on How to change model and variable values as a local variable in the method.

Thanks for visiting :) Let me know if you have some suggestions or feedback for this post in the comment section. Looking for any tutorial or demo on FreakyJolly, just drop me a message here

Leave a Reply

avatar
  Subscribe  
Notify of