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();
});
}
}
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();
}
}