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

Avatar photo

theCodeCampus
Developer at thecodecampus </>

Our knowledge is not simply gained through reading - it is trained, tested and constantly being expanded. Because first and foremost, we are all developers at W11K. The know-how that we acquire here as developers, consultants and information architects flows immediately into our training courses and articles for 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.