typescript - Angular 2 - 在输入变量更改时更改邻居输入变量

标签 typescript angular angular2-components angular2-inputs

我想在更改输入参数时执行一些操作。假设我有一个 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/

相关文章:

javascript - 装饰器 : "this" is undefined when accessed in descriptor. 值

typescript - 有没有办法将 "extract"类型的 TypeScript 接口(interface)属性?

angular - Ionic2 - 每当我使用 navCtrl 推送新页面/组件时,选项卡就会消失

Angular 2 : Component Interaction, 可选输入参数

angular - 在 ngClass 的条件实现中使用变量

typescript - 在 typescript 中使用 SES 发送电子邮件

angular - Ngmodel 值更新错误?

Angular 2 表单验证不起作用

angular - SQLite Mocking 不适用于 ionic

angular - 如何获取 angular2 组件的父 DOM 元素引用