7

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.

0

3 Answers 3

15

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;
         }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

You can use a setter.

@Input('input')
set input(value: numer) {
    this.currentNumber = this.data.someOtherNumber+this.input.numberIneed;
}

Comments

2

You can use ngOnChanges. If input changes this function is called:

ngOnChanges(){
  this.currentNumber = this.data.someOtherNumber + this.input.numberIneed;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.