Check out our Angular Book Series.

Creating Angular Directives Part 3 - Exposing Properties

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.

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

Expose New Properties

The directive as is is hard coding the style values inside the directive. That is horrible use of encapsulation, and limits reuse. Let's open those up. Open up reverse.directive.ts:

@Input() regularCSSClass: string;
@Input() reversedCSSClass: string;

I added one input for the regularCSSClass and one for the reversedCSSClass. Now move to the changeState() function:

changeState() {
if (this.reversedState) {
this.renderer.removeClass(this.el.nativeElement, this.regularCSSClass);
this.renderer.addClass(this.el.nativeElement, this.reversedCSSClass);
} else {
this.renderer.removeClass(this.el.nativeElement, this.reversedCSSClass);
this.renderer.addClass(this.el.nativeElement, this.regularCSSClass);

Instead of accessing hard coded values as the CSS Class is added, or removed, from the native element the variables are added.

Notice how the values have no default styles. To solve that we'll make sure to call the changeState() method when ngOnInit() runs, which will be after the property values are set. First implement the OnInit interface as part of the class definition:

export class ReverseDirective implements OnInit {

Then add the ngOnInit() method:

ngOnInit() {

This will make sure that the default states are set after the component is initialized. Open up create-attribute-directive.component.html and add in our two new properties:

<button (click)="reverseState()"

Reverse State

Angular's magic under the hood will know the new attributes belong to the directive and will pass in those values.

Rerun the app:

Then click the button:

The new Angular directive inputs were set up as regular HTML attributes with string values, but we could set them up as Angular attributes with an Angular expression as the value. In the simplest form, like this:

<button (click)="reverseState()"

Reverse State

The Angular expression is a literal string, and the regularCSSClass and reversedCSSClass are enclosed in brackets, signifying they are properties.

What's Next?

The next part of this series will show you how to use events as part of a directive.

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