Angular 2.x观察变量变化 [英] Angular 2.x watching for variable change

查看:559
本文介绍了Angular 2.x观察变量变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正从角度1.x迁移到2.x但是我的大脑仍然在角度1.x中思考,对于愚蠢的问题感到抱歉。

I'm migrating from angular 1.x to 2.x but my brains still think in angular 1.x so sorry for silly questions.

我需要什么当我的范围变量组件属性之一发生变化时,我会采取一些措施。我找到了解决方案,但我认为应该有更好的解决方案

What I need is to take some action when one of my scope variables component properties changes. I found a solution but I think there should be better solution

export class MyApp {
    router: Router;
    location: Location;
    fixed: boolean = true;

    private set isFixed(value:boolean) {
        this.fixed = value;

        //TODO: look here
        console.log('isFixed changed', value);
    }

    private get isFixed():boolean {
        return this.fixed;
    }

    constructor(router: Router, location: Location) {
        this.router = router;
        this.location = location;
    }
}

查看行控制台.log('isFixed changed',value); 这就是我需要的东西,它正在发挥作用。但是我通过声明 getter setter 来实现它,但是没有更好的解决方案来观察变量?就像在角度1.x中 $ scope。$ watch

Look at the line console.log('isFixed changed', value); It's what I need and it's working. But I made it by declaring getter and setter, but isn't there a better solution to watch variables? Like in angular 1.x was $scope.$watch?

我认为我的组件代码应该像

I think my component code should look like

export class MyApp {
    router: Router;
    location: Location;
    isFixed: boolean = true;

    //TODO: $watch for isFixed change {
        console.log('isFixed changed', value);
    // }

    constructor(router: Router, location: Location) {
        this.router = router;
        this.location = location;
    }
}


推荐答案

你可能想要实现 OnChanges 接口并实现 ngOnChanges()方法。
只要其中一个组件输入或输出绑定值发生更改,就会调用此方法。
另请参阅 https://angular.io/docs/ts/latest/guide/ lifecycle-hooks.html

You might want to implement the OnChanges interface and implement the ngOnChanges() method. This method is called whenever one of the components input or output binding value changes. See also https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

Dart代码示例

  @Input() bool fixed;

  @override
  void ngOnChanges(Map<String, SimpleChange> changes) {
    print(changes);
  }

这篇关于Angular 2.x观察变量变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆