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 šŸ˜‰ )

tl;dr;

Solution

You could use theĀ OnChangesĀ interface with theĀ ngOnChanges(changes: SimpleChanges): void Method to listen to all @Input() changes.

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.

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.

Related Posts

Admin Admin
Developer at thecodecampus </>


Leave a Reply

Add code to your comment in Markdown syntax.
Like this:
`inline example`

```
code block
example
```

Your email address will not be published.