Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subscribe on variable in Angular 2?

Tags:

angular

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

like image 957
OPV Avatar asked Oct 18 '25 06:10

OPV


1 Answers

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

like image 112
Tyler Jennings Avatar answered Oct 19 '25 21:10

Tyler Jennings



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!