How can you create a custom structural directive in Angular?

Creating Custom Structural Directives in Angular

In Angular, custom structural directives can be created using the @Directive decorator. Angular directives are one of the fundamental concepts of Angular apps, as they allow developers to supplement or modify the DOM (Document Object Model). They are a useful feature when you want to reuse component logic, reduce boilerplating, and make your code more readable.

To create a custom structural directive, you start by declaring a class, then attach @Directive decorator to it. The @Directive decorator is used to mark a class as an Angular directive and provide additional metadata that determines how the directive should be processed, instantiated, and used at runtime.

Practical Example

To illustrate this concept, let’s create a simple custom structural directive, appUnless:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

  selector: '[appUnless]'
export class UnlessDirective {
  private hasView = false;

    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef) { }

  @Input() set appUnless(condition: boolean) {
    if (!condition && !this.hasView) {
      this.hasView = true;
    } else if (condition && this.hasView) {
      this.hasView = false;

In the code above, appUnless is a structural directive that creates or destroys a part of the DOM tree based on the evaluation of a condition.

Good Practices

When creating custom structural directives, it's a good practice to consider the following:

  1. Encapsulation: Directives should encapsulate their own behaviour. This means that directives should not implicitly use or change properties of other directives or components.

  2. Single Responsibility: Directives should only focus on a single task. If you need a directive that performs multiple functions, consider breaking it down into multiple simpler directives.

  3. Naming Conventions: Prefix your directive selector with something unique to avoid selector conflicts with third-party libraries. Angular's best practice is using app as prefix.

In conclusion, @Directive decorator is the correct way to create custom structural directives in Angular. It provides a powerful way to enhance your HTML by enabling reusability and promoting cleaner, more modular code.

Do you find this helpful?