javascript - Angular 2.x 观察变量变化

标签 javascript angular

我正在从 angular 1.x 迁移到 2.x,但我的大脑仍然以 angular 1.x 思考,很抱歉提出愚蠢的问题。

我需要的是在我的 scope variables 组件属性之一发生变化时采取一些行动。我找到了解决方案,但我认为应该有更好的解决方案

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;
    }
}

查看行 console.log('isFixed changed', value); 这是我需要的,它正在工作。但是我是通过声明gettersetter 来实现的,但是没有更好的方法来监视变量吗?就像在 Angular 1.x 中是 $scope.$watch?

我认为我的组件代码应该是这样的

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 接口(interface)并实现 ngOnChanges() 方法。 只要其中一个组件输入或输出绑定(bind)值发生变化,就会调用此方法。 另见 https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

Dart 代码示例

  @Input() bool fixed;

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

关于javascript - Angular 2.x 观察变量变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34434057/

相关文章:

html - Angular 2 : Forms with Material Design: ng-message doesn't work like it should

javascript - 如何使用phantomjs创建gif?

javascript - 在 MeteorJS 中检查用户组

javascript - 如何使用提示(如简单的计算器)对数字求和?

angular - 单元测试 valueChanges 可观察管道

javascript - angular 4减少html内容

javascript - Bootstrap 月份选择器无法正常工作

javascript - 更改单击菜单列表上的事件类别

angular - 具有动态变化子形式的复杂 Angular 形式

angular - ng 测试 - 语法错误 : Unexpected token 'const'