Advertisement
Beginner Angular, Directives

What is a directive in Angular and what are the three main types?

Short answer

A directive is a class that adds behavior to an element in your template. Component directives are directives with their own template. Structural directives, like the older asterisk ngIf, change the layout by adding or removing elements.

Save Angular mock interview
Advertisement
AModel answer
A directive is a class that adds behavior to an element in your template. Component directives are directives with their own template. Structural directives, like the older asterisk ngIf, change the layout by adding or removing elements. Attribute directives, like ngClass, change the appearance or behavior of an existing element without adding or removing it.
// Attribute directive example
<div [ngClass]="{ active: isActive }">Content</div>

// Structural directive example
<p *ngIf="isVisible">This text is conditionally shown</p>
Real-world example
A navigation menu highlights the currently active link using the ngClass attribute directive, while a separate section of the page is conditionally shown or hidden using a structural directive.
Likely follow-ups
  • What is the difference between a structural directive and a component, given both can affect the template?
  • Why does a structural directive's name in older syntax start with an asterisk?
Related topics