Reputation: 3677
I have a directive that should update some internal value based on input's ngModel. This works fine when user types values in manually, but stops working when ngModel is changed from the component.
Component template:
<input [(ngModel)]="myValue" myExample>
Changing ngModel in component:
ngOnInit() {
this.getDataFromApi()
.then((result) => {
this.myValue = result;
})
}
Directive:
import { Directive, OnInit } from '@angular/core';
import { NgModel } from '@angular/forms';
@Directive({
selector: '[myExample][ngModel]',
providers: [NgModel],
host: {
'(ngModelChange)' : 'onModelChange($event)',
}
})
export class myExampleDirective implements OnInit {
private _valueInDirective;
constructor(private _element: ElementRef, private _model: NgModel) { }
onModelChange(event) {
this._valueInDirective = event;
}
}
If the ngModel is updated from controller after an API call, ngModelChange in directive doesn't fire and the _valueInDirective is not updated. How to make sure that every time the ngModel is updated, value in directive will be changed as well?
Upvotes: 6
Views: 8080
Reputation: 3677
I experimented with DoCheck
hook, but it turned out extremely inefficient. This is the solution I ended up with and I'm happy with:
import { Directive, OnInit } from '@angular/core';
import { NgModel } from '@angular/forms';
@Directive({
selector: '[myExample][ngModel]',
providers: [NgModel]
})
export class myExampleDirective implements OnInit {
private _valueInDirective;
constructor(private _model: NgModel) { }
ngOnInit() {
this._model.valueChanges.subscribe((event) => {
this._valueInDirective = event;
// do other stuff
});
}
}
Upvotes: 3