Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect variable change in Angular2

I have the following config object which is set before the constructor is running:

config: Object = {
     onSlideChangeEnd : function(slide:any) {
          this.currentSlideIndex = slide.activeIndex;
     }
};

I want to notify a service about the change, the problem is that the service is not available yet when the configuration is set:

 constructor(private user: UserService,
             private layout: LayoutService) {
 }

How can I notify the service on this variable change?

like image 221
Yuvals Avatar asked Jan 28 '17 22:01

Yuvals


People also ask

How do you identify changes in Angular components?

To run the change detector manually: Inject ChangeDetectorRef service in the component. Use markForCheck in the subscription method to instruct Angular to check the component the next time change detectors run. On the ngOnDestroy() life cycle hook, unsubscribe from the observable.

What is change detection How does change detection mechanism work?

Change detection is the process through which Angular checks to see whether your application state has changed, and if any DOM needs to be updated. At a high level, Angular walks your components from top to bottom, looking for changes.


1 Answers

Well, as suggested use Observables, this is not really such a big hassle and it works quite well. It's not more than a few lines actually.

Declare in some common service, a service that they share as same, e.g a service declared as provider in that module, so that you do not end up with two instances of the same service. Add a Subject to that service and a method to emit value:

public configObservable = new Subject<number>();

emitConfig(val) {
  this.configObservable.next(val);
}

And in the component you need to set the config:

emit(val) { // your value you want to emit
  this.myService.emitConfig(val);
}

And then subscribe to the value where you need it:

constructor(private myService: MyService) {
  this.myService.configObservable.subscribe(value => {
    this.value = value;
  })
}

Working plunker with above code in a parent-child interaction:

Plunker

As to your comment about @Input(), that works well when a parent component-child interaction, so that wouldn't really work for you in this case.

like image 75
AT82 Avatar answered Sep 25 '22 06:09

AT82