Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call function each time model changes in angular 2?

Tags:

I've got a custom select component which sets the model when you click on a li item, but since I manually call this.modelChange.next(this.model) every time I change the model it's quite messy and repeatable which I want to avoid.

So my question is if there's something similar to $scope.$watch where I can watch if a value changes and then call this.modelChange.next(this.model) each time it happens.

I've been reading about Observables but I can't figure out how this is supposed to be used for just a simple value since all examples I see are with async requests to external api:s.

Surely there must be a more simple way to achieve this?

(Not that I can't use ngModelChanges since I'm not actually using an input for this).

import {Component, Input, Output, EventEmitter, OnInit, OnChanges} from 'angular2/core';  @Component({   selector: 'form-select',   templateUrl: './app/assets/scripts/modules/form-controls/form-select/form-select.component.html',   styleUrls: ['./app/assets/scripts/modules/form-controls/form-select/form-select.component.css'],   inputs: [     'options',     'callback',     'model',     'label'   ] })  export class FormSelectComponent implements OnInit, OnChanges {   @Input() model: any;   @Output() modelChange: EventEmitter = new EventEmitter();    public isOpen: boolean = false;    ngOnInit() {      if (!this.model) {       this.model = {};     }      for (var option of this.options) {        if (option.model == (this.model.model || this.model)) {         this.model = option;        }     }   }    ngOnChanges(changes: {[model: any]: SimpleChange}) {     console.log(changes);     this.modelChange.next(changes['model'].currentValue);   }    toggle() {     this.isOpen = !this.isOpen;   }    close() {     this.isOpen = false;   }    select(option, callback) {     this.model = option;     this.close();      callback ? callback() : false;   }    isSelected(option) {     return option.model === this.model.model;   } } 

Edit: I tried using ngOnChanges (see updated code above), but it only runs once on initialization then it doesn't detect changes. Is there something wrong?

like image 362
Chrillewoodz Avatar asked Mar 28 '16 12:03

Chrillewoodz


People also ask

How Angular 2 detect changes?

How is change detection implemented? Angular can detect when component data changes, and then automatically re-render the view to reflect that change.

How do you call a function every 10 seconds TypeScript?

Use the setInterval() method to call a function every N seconds in TypeScript, e.g. setInterval(myFunction, seconds * 1000) . The first parameter the method takes is the function that will be called on a timer, and the second parameter is the delay in milliseconds. Copied!

What is OnChange Angular?

OnChangeslinkA lifecycle hook that is called when any data-bound property of a directive changes. Define an ngOnChanges() method to handle the changes. interface OnChanges { ngOnChanges(changes: SimpleChanges): void }


1 Answers

So my question is if there's something similar to $scope.$watch where I can watch if the value of input property model changes

If model is a JavaScript primitive type (Number, String, Boolean), then you can implement ngOnChanges() to be notified of changes. See cookbook example and lifecycle doc, OnChanges section.
Another option is to use a setter and a getter. See cookbook example.

If model is a JavaScript reference type (Array, Object, Date, etc.), then how you detect changes depends on how the model changes:

  • If the model reference changes (i.e., you assign a new array, or a new object, etc.), you can implement ngOnChanges() to be notified of changes, just like for primitive types.
  • However, if the model reference doesn't change, but some property of the model changes (e.g., the value of an array item changes, or an array item is added or removed, or if an object property value changes), you can implement ngDoCheck() to implement your own change detection logic.
    See lifecycle doc, DoCheck section.
like image 78
Mark Rajcok Avatar answered Oct 13 '22 13:10

Mark Rajcok