Back in the days of AngularJS, we could easily listen for variable changes using $watch
, $digest
... but with the newer versions like Angular 5 and 6, this feature is no longer available.
In the current version of Angular, handling variable changes has become a part of the component lifecycle.
I delved into official documentation, various articles, and particularly sought answers on Angular 5 change detection on mutable objects to learn how to observe changes in variables (class properties) within a TypeScript class / Angular.
The recommended approach nowadays is:
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 {
@Input() input1:string;
@Input() input2:string;
myProperty_1: boolean
myProperty_2: ['A', 'B', 'C'];
myProperty_3: MysObject;
constructor() { }
ngOnInit() { }
ngOnChanges(changes: SimpleChanges) {
//Action for change
}
ngDoCheck() {
//Action for change
}
}
This approach only works for @Input()
properties!
If I need to monitor changes in my component's own properties (myProperty_1
, myProperty_2
, or myProperty_3
), the above solution won't suffice.
Can anyone provide assistance in resolving this issue? Ideally, I am looking for a solution that is compatible with Angular 5.