Detecting change in value in angular

420 Views Asked by At

I am working on a angular application. I have certain set of screens. I have a variable who's value will always be in integer. For some screens this variable value is 1 and for some it is 2.

I want to detect change in this variable. For example for screen 1, myVal is 1 and for screen 2, myVal becomes 2 and for screen 5, myVal again becomes 1. I want to open a pop up when myVal value is becomes 2 from 1. The problem I am facing is when I am on screen 4 and when I send my response from rabbitMq the value of myVal immediately becomes 1 and my pop up if condition doesnot get executed.

How can I do that?

1

There are 1 best solutions below

3
On

imagine you has a service -remember that a service is shared while whole live of your application

@Injectable({
  providedIn: 'root',
})
export class DataService {

  variableChange=new Subject<number>()
  constructor() { }

  sendValue(value)
  {
    this.variableChange.next(value)
  }
}

Any component that inject the service and subscribe to variableChange(*) -you can use distinctuntilChange to make something only if change the value- like

 constructor(dataService:DateService){}
 ngOnInit()
 {
    this.dataService.variableChange.pipe(
        distinctUntilChanged())
        .subscribe(res=>{
            ..make something..
        })
 }

receive a change from any another component that also inject the service in constructor and make a next

 this.dataService.variableChange.next(value)

If you want, you can use a getter of the variable in the way

_variable;
get variable()
{
     return this._variable
}
set variable(value)
{
     this._value=value;
     this.dataService.variableChange.next(value)
}

//an instruction like
this.variable=2 //execute the variableChange

(*)e.g. we can has a main.app that inject the constructor and subscribe

Our main.component can be, e.g.

<ng-container ngIf="variable==2">
   <app-header></app-header>
</ng-container>

<router-outlet></router-outlet>

variable:number 
ngOnInit()
 {
    this.dataService.variableChange.pipe(
        distinctUntilChanged())
        .subscribe(res=>{
            this.variable=res
        })
 }

A component that has in the ngOnInit()

ngOnInit()
{
   this.dataService.variableChange.next(2)
}

When was loaded in the router-outlet makes that the "app-header" appears. If out component has a button

   <button (click)="click()">
   click()
   {
       this.dataService.variableChange.next(0)
   }

When click the button the "app-header" disappears