在 AngularJS 中,我们可以使用 $watch
, $digest
来监听变量的变化……新版本的 Angular (5, 6) 不再可能。
在 Angular 中,这种行为现在是组件生命周期的一部分。
我查看了官方文档、文章,尤其是 关于可变对象的 Angular 5 变化检测,以了解如何监听 TypeScript 类/ Angular 中的变量(类属性)变化
今天提出的是:
import { OnChanges, SimpleChanges, DoCheck } from '@angular/core';
@Component({
selector: 'my-comp',
templateUrl: 'my-comp.html',
styleUrls: ['my-comp.css'],
inputs:['input1', 'input2']
})
export class MyClass implements OnChanges, DoCheck, OnInit{
//I can track changes for this properties
@Input() input1:string;
@Input() input2:string;
//Properties what I want to track !
myProperty_1: boolean
myProperty_2: ['A', 'B', 'C'];
myProperty_3: MysObject;
constructor() { }
ngOnInit() { }
//Solution 1 - fired when Angular detects changes to the @Input properties
ngOnChanges(changes: SimpleChanges) {
//Action for change
}
//Solution 2 - Where Angular fails to detect the changes to the input property
//the DoCheck allows us to implement our custom change detection
ngDoCheck() {
//Action for change
}
}
这仅适用于 @Input()
属性!
如果我想跟踪组件自身属性的变化( myProperty_1
, myProperty_2
或 myProperty_3
),这将不起作用。
有人可以帮我解决这个问题吗?最好是与 Angular 5 兼容的解决方案
原文由 L Y E S - C H I O U K H 发布,翻译遵循 CC BY-SA 4.0 许可协议
您仍然可以通过
KeyValueDiffers
通过DoCheck
lifehook 检查组件的字段成员值更改。看 演示。