update
Angular2 causes this error when it looks like change detection itself has side effects that causes model change which usually indicates a bug or a design flaw that causes Angular2 applications to work inefficiently.
To hide such an issue you can just enable prodMode
.
A workaround for model changes in lifecycle methods call ChangeDetectorRef.detectChanges()
to make it explicit that this model change 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();
}
}
}
original
You can either use setTimeout()
setTimeout()
is a sledgehammer method because it causes a change detection cycle for the whole application.
@Input()
set type(type: string) {
if (type === "today") {
this.date = new Date();
setTimeout(() => this.dateChange(this.date));
}
}
This is necessary when type
is updated by change detection because Angular2 doesn't like when change detection causes changes.
Another way is to use ngOnChanges()
but this is also called by change detection and also needs 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 difference between these two approaches is that the first executes the code for every change, the last only for changes caused by bindings.