POV
POV

Reputation: 12025

How to subscribe on variable in Angular 2?

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

Upvotes: 4

Views: 10246

Answers (2)

Tyler Jennings
Tyler Jennings

Reputation: 8921

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 => ...)

Upvotes: 2

Related Questions