角度2:如何检测组件上输入属性的属性更改? [英] Angular 2: how do I detect attribute changes to input attributes on a Component?
问题描述
我有一个看起来像这样的Angular 2控制器:
I've got an Angular 2 Controller which looks like this:
@Component({
selector: 'my-component',
template: '<div>The value is: {{ value }}</div>',
})
class MyComponent implements OnInit {
@Input()
value: string;
@Output
valueChange = new EventEmitter<number>();
ngOnInit() {
this.valueChange.subscribe(value => {
console.log('new value:', value); // <-- does not get triggered
});
}
}
但是当value
的值从模板绑定更改时:
But when the value of value
changes from a template binding:
<my-component [value]="someValue" /> <!-- valueChange not triggered! -->
valueChange
事件不会被触发,因此即使模板正确更新并显示新值,组件也不知道它已被更改.
The valueChange
event isn't triggered so, even though the template correctly updates and shows the new value, the component doesn't know it's been changed.
如何检测控制器上的输入属性何时更改?
How can I detect when input attributes on my controller are changed?
推荐答案
在我看来,Output
是让您的组件向其他人发出事件,以便他们在必要时可以更新其视图,它仅应用于所做的更改在内部需要广播(因此名称为Output
).在Input
更改上触发Output
事件可能会导致意外行为(因为现在对于内部和外部的所有更改都触发了valueChange
,实际上不再是Output
了.)
In my opinion, Output
is for your component to emit event to others so they would update their view if necessary, it should only be used for changes made internally that need to be broadcast out (hence the name Output
). Triggering an Output
event on Input
changes may cause unexpected behavior (as now that valueChange
is triggered for all the changes both inside and outside, and not really an Output
anymore).
以您为例,如果您想在value
更改时做一些事情,可以将其设置为设置器:
In your case, if you want to do stuff when your value
changes, you can make it a setter:
private _value: string;
get value(): string {
return this._value;
}
@Input('value')
set value(val: string) {
this._value = val;
console.log('new value:', value); // <-- do your logic here!
}
这篇关于角度2:如何检测组件上输入属性的属性更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!