Monday, 2 September 2019

Angular - function reference

@angular/cli: 8.2.0

This article demonstrates a powerful mechanism (yet well-known, I am sure) to pass on function references while passing data from one component to another.

This mechanism or idea can be quite helpful if you are planning to build re-usable toolbar components for your application. Reusable toolbars perform the same kind of operation most of the time. But what if, for a rare use-case, you want an existing toolbar button to perform slightly differently?

Let us see the setup here. We have an app-component and an app-toolbar component. The app-toolbar takes in an array of elements and renders some buttons with some actions.

With a usual use-case, each button is meant to perform a known action.

So far, nothing defferent from the usual. But let's say, I want to perform a more complex operation during Delete operation, for which it might be difficult to write a reusable piece of code.

For such use cases, I would pass on a method from the calling component, where I have all the logic available. Not just that, I would also have to pass on the AppComponent class reference, bound to the method, so that the correct method from the correct TypeScript class gets executed.

Now when I click on Delete button, I see that my AppComponent class' method gets executed.

You can download the source from GitHub.


No comments:

Post a Comment