在AngularJS中,我们可以使用$watch
$digest
...这在Angular(5,6)的新版本中不再可能.
在Angular中,这种行为现在是组件生命周期的一部分.
我查看了官方文档、文章,尤其是Angular 5 change detection on mutable objects,以了解如何在TypeScript class/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相容的溶液