What Are Angular Directives? Types, Examples & Best Practices

Estimated study time: 10 minutes. How Angular lets you extend and manipulate the DOM beyond plain HTML.

A directive is a class that adds behavior to an element in the DOM. Components are technically directives with a template, but Angular also has two other directive types built for different jobs.

1. Component Directives

Every Angular component is a directive with its own template — the most common type you'll write day to day.

2. Structural Directives

Change the structure of the DOM by adding, removing, or repeating elements. Recognizable by the leading asterisk.

<div *ngIf="isLoggedIn">Welcome back!</div>

<li *ngFor="let item of items; trackBy: trackById">
  {{ item.name }}
</li>

<div [ngSwitch]="userRole">
  <p *ngSwitchCase="'admin'">Admin Panel</p>
  <p *ngSwitchDefault>Standard User</p>
</div>

3. Attribute Directives

Change the appearance or behavior of an existing element without altering the DOM structure.

<p [ngClass]="{ 'highlight': isActive }">Status text</p>
<div [ngStyle]="{ color: textColor }">Styled text</div>

Writing a Custom Attribute Directive

@Directive({ selector: '[appHighlight]' })
export class HighlightDirective {
  constructor(private el: ElementRef) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.el.nativeElement.style.backgroundColor = '#FFF1EC';
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.el.nativeElement.style.backgroundColor = '';
  }
}

Best Practices

  • Prefer built-in directives (ngIf, ngFor, ngClass) before writing a custom one.
  • Keep custom directives focused on one behavior — don't let them grow into mini-components.
  • Always add trackBy to *ngFor over dynamic lists to avoid unnecessary re-renders.
💡 Tip: If a directive starts needing its own template or complex internal state, it's usually a sign it should be a component instead.

Built-in Control Flow in Newer Angular Versions

Recent Angular versions add a built-in control flow syntax that does the job of *ngIf, *ngFor and ngSwitch directly in the template. It needs no imports and is now the recommended style for new code:

@if (isLoggedIn) {
  <p>Welcome back!</p>
} @else {
  <p>Please sign in.</p>
}

@for (item of items; track item.id) {
  <li>{{ item.name }}</li>
} @empty {
  <li>No items yet.</li>
}

@switch (userRole) {
  @case ('admin') { <p>Admin Panel</p> }
  @default { <p>Standard User</p> }
}

The track expression is required in @for, which removes the common performance mistake of forgetting trackBy. Structural directives still work, and you will see them in many existing projects, so it is worth knowing both styles.

Building a Custom Structural Directive

A structural directive receives a template and decides whether, and how many times, to render it. This example shows content only for users with a given role:

@Directive({ selector: '[appHasRole]', standalone: true })
export class HasRoleDirective {
  private tpl = inject(TemplateRef<unknown>);
  private vcr = inject(ViewContainerRef);
  private auth = inject(AuthService);

  @Input() set appHasRole(role: string) {
    this.vcr.clear();
    if (this.auth.hasRole(role)) {
      this.vcr.createEmbeddedView(this.tpl);
    }
  }
}
<button *appHasRole="'admin'">Delete user</button>

The asterisk tells Angular to wrap the button in an ng-template and pass it to the directive. Here AuthService stands for your own service. Hiding a button is only a convenience; the server must still check permissions.

The two injected helpers do the real work. TemplateRef holds the markup that was marked with the asterisk, and ViewContainerRef is the spot in the page where that markup can be stamped out. Calling clear() first ensures the button is removed again if the input changes to a role the user does not have.

Improving the Highlight Directive

The earlier example sets styles through nativeElement. A cleaner approach binds to the host element and accepts the colour as an input, so the directive works with server-side rendering and is reusable:

@Directive({
  selector: '[appHighlight]',
  standalone: true,
  host: {
    '(mouseenter)': 'active = true',
    '(mouseleave)': 'active = false',
    '[style.backgroundColor]': 'active ? color : null'
  }
})
export class HighlightDirective {
  @Input('appHighlight') color = '#FFF1EC';
  active = false;
}
<p appHighlight="#E8F5E9">Hover over me</p>

Choosing Between a Directive, Component or Pipe

NeedBest Fit
Add behaviour to existing markup (tooltips, focus, permissions)Attribute or structural directive
A reusable piece of UI with its own markupComponent
Format a value for display (dates, currency, text)Pipe

A quick test: if you find yourself adding a template to a directive, you need a component. If you are only changing how a value looks, a pipe is lighter and easier to reuse. Directives sit in between, adding behaviour without owning any markup.

Mistakes to avoid with directives

  • Putting two structural directives on one element, which Angular does not allow; wrap one in ng-container.
  • Forgetting to import or declare the directive, so the attribute is silently ignored as plain HTML.
  • Manipulating the DOM directly with browser APIs instead of using host bindings or Renderer2.
  • Choosing a selector without a prefix, which can clash with other libraries.

Ready to go beyond the basics?

Get hands-on training, live mentorship, and placement support with Uncodemy's Angular Training Course.

Explore Angular Training Course →