block includes
include ../_util-fns
:marked
An **Attribute** directive changes the appearance or behavior of a DOM element.
:marked
# Contents
* [Directives overview](#directive-overview)
* [Build a simple attribute directive](#write-directive)
* [Apply the attribute directive to an element in a template](#apply-directive)
* [Respond to user-initiated events](#respond-to-user)
* [Pass values into the directive using data binding](#bindings)
* [Bind to a second property](#second-property)
Try the
` element will be the attribute **host**. p | Put the template in its own code #[+adjExPath('app.component.html')] | file that looks like this: +makeExample('attribute-directives/ts/app/app.component.1.html',null,'app/app.component.html')(format=".") :marked Now reference this template in the `AppComponent`: +makeExample('attribute-directives/ts/app/app.component.ts',null,'app/app.component.ts') :marked Next, add an `import` statement to fetch the `Highlight` directive and add that class to the `declarations` NgModule metadata. This way Angular recognizes the directive when it encounters `myHighlight` in the template. +makeExample('attribute-directives/ts/app/app.module.ts',null,'app/app.module.ts') :marked Now when the app runs, the `myHighlight` directive highlights the paragraph text. figure.image-display img(src="/resources/images/devguide/attribute-directives/first-highlight.png" alt="First Highlight") .l-sub-section :marked ### Your directive isn't working? Did you remember to add the directive to the the `declarations` attribute of `@NgModule`? It is easy to forget! Open the console in the browser tools and look for an error like this: code-example(format="nocode"). EXCEPTION: Template parse errors: Can't bind to 'myHighlight' since it isn't a known property of 'p'. :marked Angular detects that you're trying to bind to *something* but it doesn't know what, so it looks to the `declarations` metadata array. By specifying `HighlightDirective` in the array, Angular knows to check the import statements and from there, to go to `highlight.directive.ts` to find out what `myHighlight` does. :marked To summarize, Angular found the `myHighlight` attribute on the `
` element. It created an instance of the `HighlightDirective` class, injecting a reference to the element into the constructor where the `
` element's background style is set to yellow. .l-main-section a#respond-to-user :marked ## Respond to user-initiated events Currently, `myHighlight` simply sets an element color. The directive should set the color when the user hovers over an element. This requires two things: 1. detecting when the user hovers into and out of the element. 2. responding to those actions by setting and clearing the highlight color. To do this, you can apply the `@HostListener` !{_decorator} to methods which are called when an event is raised. +makeExample('attribute-directives/ts/app/highlight.directive.2.ts','host')(format=".") .l-sub-section :marked The `@HostListener` !{_decorator} refers to the DOM element that hosts an attribute directive, the `
` in this case. It is possible to attach event listeners by manipulating the host DOM element directly, but there are at least three problems with such an approach: 1. You have to write the listeners correctly. 1. The code must *detach* the listener when the directive is destroyed to avoid memory leaks. 1. Talking to DOM API directly isn't a best practice. :marked Now implement the two mouse event handlers: +makeExample('attribute-directives/ts/app/highlight.directive.2.ts','mouse-methods')(format=".") :marked Notice that they delegate to a helper method that sets the color via a private local variable, `#{_priv}el`. Next, revise the constructor to capture the `ElementRef.nativeElement` in this variable. +makeExample('attribute-directives/ts/app/highlight.directive.2.ts','ctor')(format=".") :marked Here's the updated directive: +makeExample('app/highlight.directive.2.ts') :marked Run the app and confirm that the background color appears when the mouse hovers over the `p` and disappears as it moves out. figure.image-display img(src="/resources/images/devguide/attribute-directives/highlight-directive-anim.gif" alt="Second Highlight") .l-main-section a#bindings :marked ## Pass values into the directive using data binding Currently the highlight color is hard-coded within the directive. That's inflexible. A better practice is to set the color externally with a binding as follows: +makeExample('attribute-directives/ts/app/app.component.html','pHost') :marked You can extend the directive class with a bindable **input** `highlightColor` property and use it to highlight text. Here is the final version of the class: +makeExcerpt('app/highlight.directive.ts', 'class') a#input :marked The new `highlightColor` property is called an *input* property because data flows from the binding expression into the directive. Notice the `@Input()` #{_decorator} applied to the property. +makeExcerpt('app/highlight.directive.ts', 'color') :marked `@Input` adds metadata to the class that makes the `highlightColor` property available for property binding under the `myHighlight` alias. Without this input metadata Angular rejects the binding. See the [appendix](#why-input) below for more information. .l-sub-section :marked ### @Input(_alias_) Currently, the code **aliases** the `highlightColor` property with the attribute name by passing `myHighlight` into the `@Input` #{_decorator}: +makeExcerpt('app/highlight.directive.ts', 'color', '') :marked The code binds to the attribute name, `myHighlight`, but the the directive property name is `highlightColor`. That's a disconnect. You can resolve the discrepancy by renaming the property to `myHighlight` and define it as follows: +makeExcerpt('app/highlight.directive.ts', 'highlight', '') :marked Now that you're getting the highlight color as an input, modify the `onMouseEnter()` method to use it instead of the hard-coded color name and define red as the default color. +makeExcerpt('attribute-directives/ts/app/highlight.directive.ts', 'mouse-enter', '') :marked To let users pick the highlight color and bind their choice to the directive, update `app.component.html` as follows: +makeExcerpt('attribute-directives/ts/app/app.component.html', 'v2', '') .l-sub-section :marked ### Where is the templated *color* property? You may notice that the radio button click handlers in the template set a `color` property and the code is binding that `color` to the directive. However, you never defined a color property for the host `AppComponent`. Yet this code works. Where is the template `color` value going? Browser debugging reveals that Angular dynamically added a `color` property to the runtime instance of the `AppComponent`. This is *convenient* behavior but it is also *implicit* behavior that could be confusing. For clarity, consider adding the `color` property to the `AppComponent`. :marked Here is the second version of the directive in action. figure.image-display img(src="/resources/images/devguide/attribute-directives/highlight-directive-v2-anim.gif" alt="Highlight v.2") .l-main-section a#second-property :marked ## Bind to a second property This example directive only has a single customizable property. A real app often needs more. Let's allow the template developer to set the default color—the color that prevails until the user picks a highlight color. To do this, first add a second **input** property to `HighlightDirective` called `defaultColor`: +makeExample('attribute-directives/ts/app/highlight.directive.ts', 'defaultColor')(format=".") :marked The `defaultColor` property has a setter that overrides the hard-coded default color, "red". You don't need a getter. How do you bind to it? The app is already using `myHighlight` attribute name as a binding target. Remember that a *component is a directive, too*. You can add as many component property bindings as you need by stringing them along in the template as in this example that sets the `a`, `b`, `c` properties to the string literals 'a', 'b', and 'c'. code-example(format="." ). <my-component [a]="'a'" [b]="'b'" [c]="'c'"><my-component> :marked The same holds true for an attribute directive. +makeExample('attribute-directives/ts/app/app.component.html', 'defaultColor')(format=".") :marked Here the code is binding the user's color choice to the `myHighlight` attribute as before. It is *also* binding the literal string, 'violet', to the `defaultColor`. Here is the final version of the directive in action. figure.image-display img(src="/resources/images/devguide/attribute-directives/highlight-directive-final-anim.gif" alt="Final Highlight") .l-main-section :marked ## Summary This page covered how to: - [Build a simple **attribute directive** to attach behavior to an HTML element](#write-directive). - [Use that directive in a template](#apply-directive). - [Respond to **events** to change behavior based on an event](#respond-to-user). - [Use **binding** to pass values to the attribute directive](#bindings). The final source: +makeTabs( `attribute-directives/ts/app/app.component.ts, attribute-directives/ts/app/app.component.html, attribute-directives/ts/app/highlight.directive.ts, attribute-directives/ts/app/app.module.ts, attribute-directives/ts/app/main.ts, attribute-directives/ts/index.html `, ',,full', `app.component.ts, app.component.html, highlight.directive.ts, app.module.ts, main.ts, index.html `) a#why-input .l-main-section :marked ### Appendix: Input properties In this demo, the `highlightColor` property is an ***input*** property of `HighlightDirective`. You've seen properties in bindings before but never had to declare them as anything. Why now? Angular makes a subtle but important distinction between binding **sources** and **targets**. In all previous bindings, the directive or component property was a binding ***source***. A property is a *source* if it appears in the template expression to the ***right*** of the equals (=). A property is a *target* when it appears in **square brackets** ([ ]) to the **left** of the equals (=) as it is does when binding to the `myHighlight` property of the `HighlightDirective`. +makeExample('attribute-directives/ts/app/app.component.html','pHost')(format=".") :marked The 'color' in `[myHighlight]="color"` is a binding ***source***. A source property doesn't require a declaration. The 'myHighlight' in `[myHighlight]="color"` *is* a binding ***target***. You must declare it as an *input* property or Angular rejects the binding with a clear error. Angular treats a *target* property differently for a good reason. A component or directive in target position needs protection. Imagine that `HighlightDirective` did truly wonderous things in a popular open source project. Surprisingly, some people — perhaps naively — start binding to *every* property of the directive. Not just the one or two properties you expected them to target. *Every* property. That could really mess up your directive in ways you didn't anticipate and have no desire to support. The ***input*** declaration ensures that consumers of your directive can only bind to the properties of the public API but nothing else.