Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
4.4k views
in Blog Post by 39 42 54
edited by

In this post, we will discuss the topic of Directive in the latest version of Angular 17.

What's Directive in Angular?

It's a special instruction in the DOM that tells the Angular framework to do something with a DOM element .

What are the types of directive in angular?

In Angular, there are three types of directives : Component , Structure , Attribute 

1) Component : Directive with a templete . 

@Component({
  selector: 'app-home',
  template:"<h1>Welcome to Home page</h1>" ,
  standalone: true,
  imports: [],
  templateUrl: './home.component.html',
  styleUrl: './home.component.scss'
})

2) Structure : Change layout of the elements by adding or removing elements

  • They often use the asterisk (*) syntax like : *ngFor - *ngIf in previous version of angular
@for (item of productList; track $index)
        {
        <tr >
            <td>{{item?.name}}</td>
            <td>
                <img src="{{item?.imageURL}}" style="width:15%;height: 15%;">
            </td>
            <td>{{item?.quantity}}</td>
            <td>{{item?.price}}</td>
        </tr>
        }@empty {
            <a>No item exist</a>
        }

3) Attribute : Modify the appearance or behavior of an element

  • They often use the ngClass - ngStyle
<div *ngIf="checkTrue">Display only when checkTrue is true from component</div>

How to create custom directive ?

1) Create directive by command : ng g directive Lightbox

2) Create a constructor that accepts a private variable from ElementRef

constructor(private elementRef : ElementRef) 
{ 
}

3) Create two Method decorator one for onMouseOver and another for onMouseOut


  // Method decorator
  @HostListener('mouseover') onMouseOver()
  {
    this.elementRef.nativeElement.style.border = `1px solid ${this.highlightColor}`;
  }

  @HostListener('mouseout') onMouseOut()
  {
    this.elementRef.nativeElement.style.border = '1px solid yellow';
  }

4) Declare a local variable that accepts the value of the @Input() property decorator

@Input() highlightColor: string = "blue";

5) Call directive to any element in html

<div appLightbox highlightColor="black">
    <h1 style="display: table-cell;">Welcome to Angular v.17</h1>
</div>

6) Result :


Conclusion

We have effectively explored various types for directives in Angular v17 through practical examples.
 


See Also 


If you don’t ask, the answer is always NO!
...