Lesson 3

When to Use Custom Components & Directives

Using custom components too much? or not enough?

PRO

Lesson Outline

When to Use Custom Components & Directives

We know that we can create our own custom components and directives, but it may not be obvious when we should do that.

You can do a lot with Ionic and Angular without creating any of your own components or directives (except for the components we use to create the "pages" in our applications). We could just use a combination of the components that Ionic provides and plain HTML/CSS to build out the functionality of the application.

In the next lesson, we walk through creating a custom "motivator" component that allows a user to cycle through motivational quotes. We build that as a component, but we could just as easily build the functionality directly into the page rather than creating a custom component.

What situations call for a custom component and what situations call for a custom directive?

Custom Directives

A directive allows us to attach behaviour to existing elements in the application - so if we want to be able to modify the behaviour of elements in our application, we could create a custom directive to do that.

In another lesson, we will walk through a basic example of building a custom ClickDisappear directive. This directive can be attached to any element in the application, and any element that it is attached to we can make disappear by clicking on it. We could implement this functionality easily enough without a directive - just set up a (click) event binding on any element we want to disappear, and then set up a corresponding function in the host components class that will trigger hiding that element.

However, the benefit of using a directive, in this case, is reasonably obvious - we can remove a lot of the grunt work by creating a custom directive that we can reuse everywhere, then all we need to do to make an element disappear when we click it is add:

<some-element click-disappear></some-element>
PRO

Thanks for checking out the preview of this lesson!

You do not have the appropriate membership to view the full lesson. If you would like full access to this module you can view membership options (or log in if you are already have an appropriate membership).