Creating a custom structural directive in Angular allows you to modify the structure of the DOM by adding, removing, or manipulating elements.

In this blog post, I’ll guide you through the process of creating a simple custom structural directive.

1. Create the Directive

To create a custom structural directive, use the @Directive decorator and the ng-template syntax in your directive’s template.

Here’s an example of a directive that conditionally renders content based on a boolean condition:

// custom-structural.directive.ts

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

@Directive({
  selector: '[appCustomStructuralDirective]'
})
export class CustomStructuralDirective {
  @Input() set appCustomStructuralDirective(condition: boolean) {
    if (condition) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }

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

In this example:

  • @Directive({ selector: '[appCustomStructuralDirective]' }): The @Directive decorator specifies that this class is a directive and can be used with the attribute appCustomStructuralDirective.
  • @Input() set appCustomStructuralDirective(condition: boolean) { ... }: This input property is a setter that receives a boolean condition. The logic inside the setter determines whether to render or remove the content based on the condition.
  • this.viewContainer.createEmbeddedView(this.templateRef);: If the condition is true, this line creates an embedded view using the provided TemplateRef and adds it to the DOM.
  • this.viewContainer.clear();: If the condition is false, this line clears the content from the DOM.

2. Use the Directive in a Component

Now that you’ve created the custom structural directive, you can use it in your components.

// app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CustomStructuralDirective } from './custom-structural.directive';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    CustomStructuralDirective
  ],
  imports: [
    BrowserModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
// app.component.html

<div *appCustomStructuralDirective="isConditionMet">
  This content is conditionally rendered.
</div>

<button (click)="toggleCondition()">Toggle Condition</button>
// app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  isConditionMet: boolean = true;

  toggleCondition() {
    this.isConditionMet = !this.isConditionMet;
  }
}

In this example:

  • <div *appCustomStructuralDirective="isConditionMet">: The *appCustomStructuralDirective syntax is used to apply the directive to the <div> element, and the isConditionMet property determines whether the content is rendered.
  • <button (click)="toggleCondition()">Toggle Condition</button>: The button calls the toggleCondition() method, which toggles the value of isConditionMet to demonstrate the dynamic behavior of the directive.

Conclusion

Creating a custom structural directive in Angular allows you to add dynamic and conditional behavior to your templates.

By leveraging the power of structural directives, you can create more flexible and reusable components that adapt to changing conditions. This example provides a foundation for building custom structural directives tailored to your application’s specific requirements.

Similar Posts