gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:23:07 24 4
gpt4 key购买 nike

我正在从 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com