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
});
}
}
But when the value of value
changes from a template binding:
<my-component [value]="someValue" /> <!-- valueChange not triggered! -->
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?
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).
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!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With