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.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  
  isWorking:boolean;

  constructor() {
	//Initialize value to false
    this.isWorking = false;
  }
  changeValue(booleanValue){
    //Converting true to false or false to true
	booleanValue = !booleanValue;
  }
}

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.

<div (click)="changeValue(isWorking)">
      {{isWorking}} 
</div>

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:

changeValue(booleanValue){
     //Converting true to false or false to true
     this.isWorking = !booleanValue;
}

 

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.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  
  data:any;

  constructor() {
	//Initialize value to false
    this.data.isWorking = false;
  }
  changeValue(booleanValue){
    //Converting true to false or false to true
	booleanValue.isWorking = !booleanValue.isWorking;
  }
}

In view, we will pass data as the parameter.

<div (click)="changeValue(data)">
      {{isWorking}} 
</div>

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

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments