我想在更改输入参数时执行一些操作。假设我有一个 DatePicker 组件,它有一个 type
输入变量,我想在类型更改时使用另一个 date
变量执行一些操作。如何做到这一点?
export class DatePicker {
@Input()
date: Date;
@Output()
dateChange = new EventEmitter();
@Input()
set type(type: string) {
if (type === "today") {
this.date = new Date();
this.dateChange(this.date); // because of this change change detector will throw error
}
}
}
错误:检查后表达式已更改。
最佳答案
更新
当 Angular2 看起来像变化检测本身具有导致模型变化的副作用时,Angular2 会导致此错误,这通常表示导致 Angular2 应用程序工作效率低下的错误或设计缺陷。
要隐藏这样的问题,您只需启用prodMode
。
生命周期方法调用 ChangeDetectorRef.detectChanges()
以明确表示此模型更改是有意的
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();
}
}
}
原创
您可以使用 setTimeout()
setTimeout()
是一个大锤方法,因为它会导致整个应用程序的变化检测周期。
@Input()
set type(type: string) {
if (type === "today") {
this.date = new Date();
setTimeout(() => this.dateChange(this.date));
}
}
当 type
被变化检测更新时这是必要的,因为 Angular2 不喜欢变化检测导致变化。
另一种方法是使用 ngOnChanges()
但这也是通过更改检测调用的,并且还需要 setTimeout()
解决方法
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));
}
}
}
}
这两种方法的区别在于,第一种方法对每次更改都执行代码,最后一种方法仅针对绑定(bind)引起的更改。
关于typescript - Angular 2 - 在输入变量更改时更改邻居输入变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38036548/