November 21, 2018
Call a method on @Input() change
Problem
You probably already run into this issue. Inside a component, you want to react to the change of an @Input()
value e.g. by calling a method of your component.
For @Input() filter: string
@Input()
1 2 |
@Input() filter: string; |
tl;dr;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
private _filter: string; @Input() set filter(value: string) { this._filter = value; if (value !== null) { // call your stuff this.filterMyData(value); } } get filter() { return this._filter; } |
Solution
You could use theĀ OnChangesĀ interface with theĀ ngOnChanges(changes: SimpleChanges): void
Method to listen to all @Input()
changes.
1 2 3 4 5 6 7 8 |
@Input() set filter(value: string) { if (value !== null) { // call your stuff this.filterMyData(value); } } |
But you also can use the TypeScript setters for member variables. This can be seen in the code example above. If Input()
null
null
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
private _filter: string; @Input() set filter(value: string) { this._filter = value; if (value !== null) { // call your stuff this.filterMyData(value); } } get filter() { return this._filter; } |
If you still need the data in the template, you can also write a getter and store the value in a private member variable. If you access filter
in your template, the getter will be called and returns the actual data.