4

I have got an variable in component was declared as:

public filter: Filter = {};

In template I bind this object like as:

<input [ngModel]="filter.name" value=""/>
<input [ngModel]="filter.secondname" value=""/>

How to listen changes this variable(object) filter?

I mean something like this:

this.filter.subscribe().then(changes => { // Call method here })

PS: I dont want to use event ngChange="" for each input elements

2

2 Answers 2

2

If you want to subscribe to it, then you must make it an observable that can be subscribed to. ie

filter: Observable<Filter>;

Then if you retrieve the data from a service, instead of subscribing to the service, just save it to the variable. ie:

filter = this.someService.getFilter();

Or if you are not using a service to retrieve the Filter data, you can create an observable with the value you want: this.filter = Observable.of(myFilter);

Then you'll be able to subscribe to this.filter wherever you need to: this.filter.subscribe(data => ...)

Sign up to request clarification or add additional context in comments.

3 Comments

I dont need subscribe to service, I need subscribe on changes of variable
Right. You don't have to use a service, but in one form or another you need filter to be an observable in order to subscribe to it. Your two main options are to use Observable.of(value) to turn the value into an observable or if you used a service to just capture the observable from the service.
I will try, the issue the follow: there is an table with some rows. In each rows are several select lists. This table is designed by ngFor. When I change selectlist it changes global model in NgFor. So I need to store only changes rows, not afecting global model.
1

You can use Javascript getter and setter methods.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set

3 Comments

I am not sure in that
With Object.defineProperty, we can now define getter and setter functions for an object property. What that does is, whenever there is an assignment for that property name, the setter function gets called and whenever you ask for that property name, the getter function gets called. So now, you can do the needful inside the setter function. For further reference please checkout the Links provided above.
I just wrote a blog post that demonstrates this here: blogs.msmvps.com/deborahk/filtering-in-angular Check out the listFilter getter and setter and how I use it to refilter the data on every change to its value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.