Check out our Angular Book Series.

Creating Angular Directives Part 5 - Applying One Directive to Different Elements

I'm updating my Learn With tutorial books that teach Angular Development for Angular 8. I decided to include a deep dive into Angular Directives. This series of posts is a snippet of what will be in the full series, and is focused on creating attribute directives.

Check out Part 1, with project setup and a starter directive and part 2 that introduces the renderer2, and part 3 that discusses input properties, and Part 4 which covers event dispatching.

We have created a directive named reverse which will toggle CSS Between two separate states.

Using the Directive Multiple Times

All our samples so far have been applying the styles to the button, but we can easily use this same directive on other elements; here it is in a p tag and a div:


<p [appReverse]="reversedState"
regularCSSClass="regular"
reversedCSSClass="reversed">

The directive in a p!
</p>
<div [appReverse]="reversedState"
regularCSSClass="regular"
reversedCSSClass="reversed">

The directive in a div!
</div>

The button is still in the view, and can be used to toggle:

Click the button and everything is reversed:

This is where we start to see the real power of encapsulating this in a directive. We are now writing simpler code than we would have if we were trying to do this using ngClass. Let's add four new styles into the create-attribute-directive.component.css:


.regular-red {
background: #ffffff;
color: #ff0000;
}

.reversed-red {
background: #ff0000;
color: #ffffff;
}

.regular-blue {
background: #ffffff;
color: #0000ff;
}

.reversed-blue {
background: #0000ff;
color: #ffffff;
}

The styles use red and white, or blue and white instead of our usual black and white. Apply them to HTML elements in create-attribute-directive-component.html:


<p [appReverse]="reversedState" regularCSSClass="regular-red" reversedCSSClass="reversed-red">
The directive in a p!
</p>

<div [appReverse]="reversedState" regularCSSClass="regular-blue" reversedCSSClass="reversed-blue">
The directive in a div!
</div>

The red style is applied to the p tag and the blue styles are applied to the div. Rerun the code:

And click to switch:

Final Thoughts

The bulk of Angular development I do is focused on creating custom components, not custom directives. But, understanding directives is important to being a good Angular developer because they give a different sort of flexibility that can be a benefit.

Be sure to check out my Learn With Series on Angular 8, which will cover this example in more detail, and even teach you all about Structural directives.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.