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.
To illustrate this concept, let’s create a simple custom structural directive, appUnless
:
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appUnless]'
})
export class UnlessDirective {
private hasView = false;
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef) { }
@Input() set appUnless(condition: boolean) {
if (!condition && !this.hasView) {
this.viewContainer.createEmbeddedView(this.templateRef);
this.hasView = true;
} else if (condition && this.hasView) {
this.viewContainer.clear();
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.
When creating custom structural directives, it's a good practice to consider the following:
Encapsulation: Directives should encapsulate their own behaviour. This means that directives should not implicitly use or change properties of other directives or components.
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.
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.