Marco Jr
Marco Jr

Reputation: 6796

Angular 5 - Detect changes on the variables

I know...there is plenty of topics like this, but I checked tons of topics and none of then applies to my issue: You can detect changes of the properties of component, you can perform a DoCheck, but the variable must be array or iterable (cannot be a simple string for example). Also can use Subject , but to set the variable you need to use a method and for some reason I don't know how to grab the value after that. Anyway, I need something very simple: A solution identical to $watch of AngularJS: Something that's stay observing any kind of change on the variable..Something that can fit on this scenario:

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

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() {
  }
  myVar = {
products : ['Alpha', 'Bravo', 'Charlie', 'Alpha' ],
dummy: 'Hello'
};
removeItem(i) {
  this.myVar.products.splice(i,1);
}
setDummy() {
  this.myVar.dummy = 'Hi !';
}
addNewKey() {
 this.myVar['newKey'] = 'Yellow';
}
addnewArray() {
  this.myVar['colors'] = ['Yellow', 'Pink', 'Blue'];
}
}

No matter what of change on myVar, I'd like to track it. How to archive it ?

Upvotes: 0

Views: 268

Answers (1)

DeborahK
DeborahK

Reputation: 60518

A few options come to mind:

1) You could use NgRx. It does a great job of providing notifications every time your data is changed ... but it is a big step adding NgRx to your application.

2) You could build a service to manage the array. The array would be private in that service and every component that needs the array would need to inject the service. The service can then provide the options to add/remove so you would always know when those actions occur.

You could then use a Subject or BehaviorSubject to provide notifications every time that the array was modifed.

3) Depending on what needs to be notified of the change, you can leverage Angular's built-in change detection. But that is only reflected in properties bound in a template.

As an example of #2 above:

export class ProductService {
    private productsUrl = 'api/products';

    private selectedProductSource = new BehaviorSubject<IProduct | null>(null);
    selectedProductChanges$ = this.selectedProductSource.asObservable();

    constructor(private http: HttpClient) { }

    changeSelectedProduct(selectedProduct: IProduct | null): void {
        this.selectedProductSource.next(selectedProduct);
    }

}

In this code I am tracking the "selected product" and sending out notifications when it has been changed.

You'd need to change this code to watch for changes to your myVar object. Instead of a changeSelectedProduct, you'd have your removeItem, setDummy, addXXX methods. Each of those methods could call .next to provide notification of the change.

Upvotes: 1

Related Questions