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.
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;
}
}
}
You can use a setter.
@Input('input')
set input(value: numer) {
this.currentNumber = this.data.someOtherNumber+this.input.numberIneed;
}
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