Directives are the fundamental building blocks in Angular used to manipulate and manage the behavior of DOM elements. The core purpose of directives is to manipulate DOM elements according to the desired output. Angular provides several built-in directives to manage forms, tables, lists, styling, and other template components. It also allows one to define custom directives in projects available throughout the project.
Key takeaways:
Angular offers three directive types including components, attribute directives, and structural directives.
Developers can create custom directives to extend Angular's functionality and manipulate the DOM.
Use the @Directive
decorator to define a custom directive in Angular.
Utilize ElementRef
to access and manipulate the host DOM element.
Use @HostListener
to respond to host element events in custom directives.
Employ @Input
decorator to accept data from the parent component into the directive.
Custom directives promote code reusability and can be shared across components.
Categories of directives
The directives in Angular are divided into two types:
Attribute directives: These modify the appearance and behavior of existing DOM elements, e.g. [(ngModel)]
Structural directives: These alter the layout of DOM by adding, removing, or replacing the elements. For example, *ngIf
and *ngFor
are examples of this type of directive.
Components are also directives with the template. No other type of directive has a template.
The build command, file structure, and declaration of both attribute and structural directives are similar. The only difference is the use of the directive as an attribute in the DOM element. Structural directives start with *
when used in a DOM element.
How to create a custom directive
Let us build a custom attribute directive alterBackground
to change the background color of the desired element from scratch.
Step 1: Generate a directive in the project
Run the following command to generate a directive in the project.