What I know, is that we call detectChanges() to trigger local change detection checks. I have seen some code that detectChanges() is called inside ngOnChanges(change) hook and I was wondering why would someone want to do something like this? I mean, if the change detection was not detected, the ngOnChanges wouldn't be called right? So why to call detectChanges inside the hook's body?
@Directive({
selector: "[dateDisplay]"
})
export class DateDisplayDirective {
@Input() ngModel: Date;
@Input() format: string;
constructor(private _elem: ElementRef, private _change: ChangeDetectorRef) { }
ngOnChanges(change) {
if (change.ngModel && change.ngModel.currentValue && change.ngModel.currentValue != change.ngModel.previousValue) {
let date = this.ngModel ? moment.utc(this.ngModel) : null;
if (this._elem.nativeElement.value != undefined) {
this._elem.nativeElement.value = date ? date.format(this.format) : "";
this._change.detectChanges();
}
}
}
}