Felipe Micali
Felipe Micali

Reputation: 847

Watch changes in component variable Angular 5

In AngularJS it was possible to $watch a variable in a controller, and this trigger was activated if the variable was changed from anywhere (from template when ng-model changed or programmatically, from controller).

I'd like to know if it's possible to accomplish the same functionality in Angular 5.

I must be able to change my variable directly from my template, without calling any functions, like this:

<button class="btn-link bc-2th" (click)="persistentComponentConfig.searchFiltersVisible = !persistentComponentConfig.searchFiltersVisible">
  FILTERS
</button>

But also I have to change it programmatically:

updateVariable () {
  this.persistentComponentConfig.searchFiltersVisible = !this.persistentComponentConfig.searchFiltersVisible
}

In both cases (there are many, actually), I have to trigger another function after the model changes.

I was able to do it by creating a reactive form and subscribing to it's 'valueChanges' property, but I don't need an entire form controller, I just need some properties to be stored in a component object to control some template *ngIf/hide/show directives and dispatch the changes to my ngrx store.

I tried to create it using Observables and BehaviorSubjects, but more boilerplate was needed to propagate all changes to my store through 'next()'. I'm just looking for something identical to AngularJS's $watch functionality.

How could I do it?

Thanks!

Upvotes: 1

Views: 13278

Answers (3)

Isaiahiroko
Isaiahiroko

Reputation: 1412

You could try using the get and set functions of a variable inside your component. Your trigger should be defined inside the set function.

This way:


  _searchFiltersVisible = null

  get searchFiltersVisible() : string {
    return this._searchFiltersVisible
  }

  set searchFiltersVisible(v: string) {

    // trigger any action you want
    // call another function, emit an event etc
    this.anyEvent.emit(v)

    this._searchFiltersVisible = v
  }

Upvotes: 1

bc1105
bc1105

Reputation: 1270

There is nothing identical to using $watch.

One common method is using getter's and setter's on a class that emit the data changes. You will have to manually subscribe to each.

Upvotes: 0

Kim Kern
Kim Kern

Reputation: 60347

Have a look at the lifecycle hooks, especially OnChanges.

It gets called, whenever at least one data property changes its value. It gets called with a SimpleChanges object, which includes the changed properties and their values.

From the docs:

ngOnChanges(changes: SimpleChanges) {
  for (let propName in changes) {
    let chng = changes[propName];
    let cur  = JSON.stringify(chng.currentValue);
    let prev = JSON.stringify(chng.previousValue);
    this.changeLog.push(`${propName}: currentValue = ${cur}, previousValue = ${prev}`);
  }
}

Upvotes: 1

Related Questions