Javascript 如何使用角度组件查看组件绑定更改
我如何倾听角度组件绑定更改并执行操作Javascript 如何使用角度组件查看组件绑定更改,javascript,angularjs,typescript,angularjs-components,Javascript,Angularjs,Typescript,Angularjs Components,我如何倾听角度组件绑定更改并执行操作 angular.module('myapp') .component('myComponent', { templateUrl: 'some.html', controller: MyController, controllerAs: 'myCtrl', bindings: { items: '<' } }); angular.mo
angular.module('myapp')
.component('myComponent', {
templateUrl: 'some.html',
controller: MyController,
controllerAs: 'myCtrl',
bindings: {
items: '<'
}
});
angular.module('myapp')
.component('myComponent'{
templateUrl:'some.html',
控制器:MyController,
controllerAs:'myCtrl',
绑定:{
items:“我发现了一种方法,但不确定它是否最有效。首先引入$scope作为依赖项,并将其设置为this.\u scope
或构造函数中的类似项。然后在我的$onInit
函数中有以下内容:
this._scope.$watch(() => {
return this.items;
},
(newVal, oldVal) => {
// Do what you have to here
});
这里的答案给了我们很大的启发:
希望它能有所帮助,在别人告诉我之前,我将使用它。目前,没有$scope,您无法使用角度观察程序,因为更改检测是基于$scope的。即使您使用HTML中的表达式,它也会
即使您创建了一些其他机制来监视,您也需要记住手动取消跟踪,并且使用$scope自动完成
现在,当项目更改时,我想使用此值执行另一个操作,
我怎么做
但是我想避免使用濒死的$scope
如果不想使用$scope
,可以使用属性设置器检测任何更改,例如:
class MyController {
private _items: string[] = []
set items(value:string[]){
this._items = value;
console.log('Items changed:',value);
}
get items():string[]{
return this._items;
}
}
const ctrl = new MyController();
ctrl.items = ['hello','world']; // will also log to the console
请注意,您不应将其用于复杂的逻辑(原因:)以下是ES5.1版本的:
使用所有主要浏览器和IE9+支持的.p.可以将$onChanges
方法添加到控制器中
$onChanges(changesObj)
在更新单向绑定时被调用。changesObj是一个哈希,其键是已更改的绑定属性的名称,值是表单的对象
以下示例处理canChange
change事件
角度模块('app.components',[])
.component('changeHandler'{
控制器:函数ChangeHandlerController(){
此.$onChanges=函数(更改){
如果(更改.取消更改)
此.performationwithvalueof(changes.canChange);
};
},
绑定:{
canChange:“这种方法可能有助于:
import { Input } from '@angular/core';
class MyComponent {
@Input set items(value) {
if (this._items !== value) {
console.log(`The value has been changed from "${this._items}" to "${value}"`);
this._items = value;
}
}
private _items;
get items() {
return this._items;
}
}
谢谢你的回答!但是我想避免使用死亡美元是的,自从“这个”之后感觉很脏变量应该是作用域并具有监视设置。我现在几乎在所有组件中都必须这样做!将值从null切换到某个值效果很好,但仅仅更改监视项的内容仍然是一个谜。如果对其他人有帮助:请注意,这只适用于较新的单向绑定语法(“
import { Input } from '@angular/core';
class MyComponent {
@Input set items(value) {
if (this._items !== value) {
console.log(`The value has been changed from "${this._items}" to "${value}"`);
this._items = value;
}
}
private _items;
get items() {
return this._items;
}
}