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?