Hi am working on AngularJS Component, need help how to use $watch inside Constructor() as below I attached my code structure.
import template from './Mypage.component.html';
export const MyComponent = {
template,
bindings: {
myData: '<'
},
controller: class MyController {
constructor($scope) {
$scope.$watch(() => this.myData, newVal => {
this._myFunction();
});
}
}
Use $onChanges()
method instead of $scope.$watch()
class MyController {
constructor() {
// Your constructor...
}
$onChanges(changedObj){
// Expect myData changes
console.log(changedObj)
}
}
More info here
You should add $scope
dependency inside $inject
array and use it in constructor should work. But please find below suggestion.
controller: class MyController {
$inject = ['$scope'];
constructor($scope) {
$scope.$watch(() => this.myData, newVal => {
this._myFunction();
});
}
}
We all know $watch
does fires on each digest cycle to update data bidnings
on page and it is bad for performance reason. Rather you could use $onChanges
lifecycle hook of angularjs component so which will only get fire when bindings value gets changed
controller: class MyController {
constructor($scope) {}
$onChanges(newVal) {
this._myFunction();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.