Input data into a Directive

We have learned that directives in Angular are incredibly powerful. We can also extend or modify the behavior or functionality of a directive by inputtting data into the directive. We'll be learning about the @Input() decorator.

A decorator is preceded by an at-symbol ( @ ) followed by the name of the decorator. A decorator in TypeScript is applied directly to either class property or method, or a class itself. When applied, a decorator annotates the class or class member with an additional behavior. Behind the scenes, this is a function that is invoked on the class or class member.

Using the @Input() decorator we can instruct the Angular framework that a property in our directive's class is an input property, and as such, the value of that property can be set via an input binding on the host element.

In our example, we have an appBtnGrow selector, which is applied to a host element. If we also specify an input property in our directive's class using the same value as the selector property value we can input data into our directive using the attribute on the host element.

To begin, we specify input property:

@Input() appBtnGrow: string

This instructs Angular that the appBtnGrow class member property is now an input that can receive a value from the host element. In this example, we're expecting a string value, which we will apply as a class to the host element. We'll be expecting either primary or secondary as the string value. If the value is primary, we'll make the button appear as a primary call-to-action button, and when secondary, the button will appear as a lesser important button in our application. Perhaps a "save" button will be a primary button, and the cancel or reset buttons will be a secondary button.

Implementing this in our host element, we'll specify the value for the input in the template as follows:

<button appBtnGrow="primary">Hover over me</button>

We don't have to use the same input binding as the directive's selector, we can also specify additional input binding properties as necessary. Perhaps this is better suited to be called "color":

@Input() color: string

And then applying this on the host element we would keep the attribute directive and also specify the additional "color" property:

<button appBtnGrow color="primary">Hover over me</button>

As you can see, inputting data into our directives is easily accomplished and greatly extends the functionality of our directives.