Reputation: 5992
I have an Input variable whose value is changed in parentComponent.
On every change, I need to update a variable called currentNumber
local to child component. At the moment I only initialise it in onInit
method, but input changes over the life time of childComponent.ts
ChildComponent.ts
@Input() input;
...
...
ngOnInit(){
this.currentNumber = this.data.someOtherNumber+this.input.numberIneed;;
}
I am aware of observers, but I feel like that declaring another service just for this is an overkill.
Upvotes: 7
Views: 10485
Reputation: 23129
You can use a setter :
private _input: number;
@Input() set input(value: number) {
this._input = value;
this.currentNumber = this.data.someOtherNumber + this.input.numberIneed;
};
get input() { return this._input; }
or ngOnChanges :
export class ChildComponent implements OnChanges {
// ...
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
if (changes['input'] && changes['input'].currentValue !== changes['input'].previousValue) {
this.currentNumber = this.data.someOtherNumber+this.input.numberIneed;
}
}
}
Upvotes: 15
Reputation: 155
You can use ngOnChanges. If input changes this function is called:
ngOnChanges(){
this.currentNumber = this.data.someOtherNumber + this.input.numberIneed;
}
Upvotes: 2
Reputation: 1746
You can use a setter.
@Input('input')
set input(value: numer) {
this.currentNumber = this.data.someOtherNumber+this.input.numberIneed;
}
Upvotes: 3