Wednesday, July 26, 2023

Angular - How to create custom structural directive?

Angular custom structural directive

Creating a custom structural directive in Angular allows you to modify the DOM based on certain conditions, extending the template syntax. Structural directives are identified by the asterisk (*) preceding the directive name in the HTML template. Let's go through the steps to create your own custom structural directive in Angular.

Step 1: Set up the Angular project: Ensure that you have Angular CLI installed. If not, you can install it using npm:
npm install -g @angular/cli
Create a new Angular project:
ng new custom-structural-directive-demo
cd custom-structural-directive-demo
Step 2: Generate the directive: Next, generate a new directive using Angular CLI:
ng generate directive customIf

This generates a new directive file named 'custom-if.directive.ts' in the 'src/app' folder.

Step 3: Implement the custom directive logic: Open the 'custom-if.directive.ts' file and implement the directive's logic. The basic structure of the directive will look like this:
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appCustomIf]'
})
export class CustomIfDirective {

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

  @Input() set appCustomIf(condition: boolean) {
    this.viewContainer.clear();

    if (condition) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    }
  }
}
Step 4: Use the custom directive in a component: Now that the directive is created, you can use it in any component's template. For example, let's use it in 'app.component.html':
<div *appCustomIf="condition">
  <p>Custom directive is working!</p>
</div>
Step 5: Add the directive to the module: To make the directive recognizable by Angular, add it to the 'declarations' array of the module where you want to use it (e.g., 'app.module.ts'):
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { CustomIfDirective } from './custom-if.directive'; // Import the directive here

@NgModule({
  declarations: [
    AppComponent,
    CustomIfDirective // Add the directive to the declarations array
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Step 6: Test the custom directive: Finally, run your Angular application using the following command:
ng serve

Now, the content inside the 'div' will be rendered when the condition used with the 'appCustomIf' directive evaluates to true; otherwise, it won't be displayed.

Happy coding!! 😊

No comments:

Post a Comment

^ Scroll to Top