Types of Directives
There are two main categories of directives, each serving different purposes:
1. Structural Directives
In Angular, structural directives are a type of directive that modify the layout of the DOM by adding, removing, or replacing elements based on certain conditions. These directives include ngIf, ngFor and ngSwitch. Let’s explore each of these directives in detail.
- *ngIf Directive: This directive helps us to conditionally include or remove elements from the DOM. Using ngIf directive we can create dynamic user interfaces.
- *ngFor Directive: This directive helps us to iterate overIterates over a collection of data and creates a DOM element for each item. This is similar to for loop in our programming languages.
- *ngSwitch Directive: This directive helps us to conditionally display an element from different section of elements based on given expression. It is similar to switch case in our programming languages.
2. Attribute Directives
These attributes are used within html tags to modify the appearance of elements, components or directives. These are applied to elements as attributes and can take inputs and react to changes in that input data.These directives include ngClass, ngStyle and ngMode. Let’s explore each of these directives in detail.
- ngClass: This attribute is used to conditionally give the classes to the elements based on the value binded to ngClass directive.
- ngStyle: This attribute is used to dynamically apply the styles to elements based on the value binded to ngStyle directive. It helps us to modify the appearance of elements on conditional basis.
- ngModel: This attribute is generally used to bind form control data to a class variable . This allows a two way binding and this is most commonly used directive with forms. It also comes with few basic validations like required,minLength , maxLength which can be directly used in our input tags.
A custom directive in Angular is a user-defined directive that extends the functionality of HTML by introducing new behaviors or attributes. Unlike built-in directives provided by Angular, custom directives are created to encapsulate specific functionality and promote code reuse within Angular applications.
Purpose of the @Directive decorator.
In Angular, Directives are defined as classes that can add new behavior to the elements in the template or modify existing behavior. The `@Directive` decorator in Angular is used to create a directive, which is a class that allows us to attach behavior to elements in the DOM. Directives are a way to extend the functionality of HTML elements and attributes in Angular applications.
Contact Us