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 example we have get an @Input() filter: string
from our parent component and if the @Input()
changes, we want to update our data in the component. (This is very constructed, of course, you should filter the data in your parent component and pass it in š )
1 |
@Input() filter: string; |
tl;dr;
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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 |
@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 the Input()
changes, the setter will be called and you can execute methods based on that data. You should check for null
here, because the initial value will be null
.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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.