Upgrade
Encountering an error in Angular2 can occur when the change detection process itself triggers model alterations, highlighting a potential bug or a flaw in the design that impacts the efficiency of Angular2 applications.
To resolve such issues, one can simply activate prodMode
.
To address model changes in lifecycle methods, you can explicitly call
ChangeDetectorRef.detectChanges()
to indicate that the model alteration is intentional.
export class DatePicker {
constructor(private cdRef:ChangeDetectorRef) {}
@Input()
date: Date;
@Output()
dateChange = new EventEmitter();
@Input()
set type(type: string) {
if (type === "today") {
this.date = new Date();
this.dateChange(this.date);
this.cdRef.detectChanges();
}
}
}
Initial
You have the option to use setTimeout()
.
setTimeout()
is a brute force method that triggers a change detection cycle for the entire application.
@Input()
set type(type: string) {
if (type === "today") {
this.date = new Date();
setTimeout(() => this.dateChange(this.date));
}
}
This becomes crucial when type
is modified by change detection, as Angular2 does not respond well to change detection-induced alterations.
Alternatively, you can utilize ngOnChanges()
, but this method is also invoked by change detection and requires the setTimeout()
workaround.
export class DatePicker implements OnChanges {
@Input()
date: Date;
@Output()
dateChange = new EventEmitter();
@Input()
set type:string;
ngOnChanges(changes:SimpleChanges) {
if(changes['type']) {
if (type === "today") {
this.date = new Date();
setTimeout(() => this.dateChange(this.date));
}
}
}
}
The distinction between these two approaches lies in the fact that the first one executes the code for every alteration, while the latter only operates for changes induced by bindings.