title: Variable Change Detection - Angular
body: <p>I'm fairly new to Angular, I work mainly with VueJS. I want to know how I can detect when a variable gets updated. I'm updating my variable through a DataService. I read about <code>ngOnChanges()</code> but I saw that this only works for inputs.</p>
  
  <p>This is pretty much my code:</p>
  
  <pre><code>import { DataService } from "../../service/my.service";
  
  export class MainPage {
    myVar: String = ""; // this is the variable I want to listen when a change is made
  
     constructor (
      private data: DataService
     ) {}
  
     ngOnInit() {
      this.data.changeVar.subscribe(message =&gt; this.myVar = message);
    }
  }
  </code></pre>
  
  <p>my.service</p>
  
  <pre><code>import { Injectable } from '@angular/core';
  import { BehaviorSubject } from 'rxjs/BehaviorSubject';
  
  @Injectable()
  export class DataService {
  
    private messageSource = new BehaviorSubject&lt;string&gt;("");
    changeVar = this.messageSource.asObservable();
  
    constructor() { }
  
    changeMyVar (message: string) {
      this.messageSource.next(message)
    }
  
  }
  </code></pre>
  
  <p>This is where I'm updating the variable.</p>
  
  <pre><code>import { DataService } from "../../service/my.service";
  
  export class AnotherPage {
    anotherVar: String = '';
  
    constructor(
      private data: DataService
    ) { }
  
    ngOnInit() {
      this.data.changeVar.subscribe(message =&gt; this.anotherVar = message)
    }
  
    myFunction () {
      this.data.changeMyVar("Hello"); // update variable to "Hello"
    }
  }
  </code></pre>
  
  <p>Any help is greatly appreciated! :)</p>