Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update variable on @Input() change

Tags:

angular

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.

like image 520
sanjihan Avatar asked Nov 28 '17 13:11

sanjihan


2 Answers

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;
         }
    }
}
like image 95
Pac0 Avatar answered Oct 02 '22 22:10

Pac0


You can use a setter.

@Input('input')
set input(value: numer) {
    this.currentNumber = this.data.someOtherNumber+this.input.numberIneed;
}
like image 23
Mateusz Witkowski Avatar answered Oct 02 '22 23:10

Mateusz Witkowski