在AngularJS中,我们可以使用
在Angular中,这种行为现在已成为组件生命周期的一部分。
我查阅了官方文档、文章,特别是Angular 5对可变对象的变更检测,以找出如何监听TypeScript类/Angular中变量(类属性)的变化。
今天提出的建议是:
$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兼容的解决方案
@Input
时才能正常工作:关于 @Input() 的评论,它在父组件-子组件交互时效果很好,所以在这种情况下它并不适用于你。 - L Y E S - C H I O U K H