Directives are instructions in the DOM (Document Object Model). It specifies how to place our business logic in Angular. The directive is markers on a DOM element that tell Angular to attach a specified behavior to that DOM element or even transform the DOM element and its children. Mostly directives in Angular starts with ng- where ng stands for Angular, and it extends the HTML.
A directive modifies the DOM by changing the appearance, behavior, or layout of DOM elements. Directives just like Component are one of the core building blocks in the Angular framework to build applications.
There are three kinds of directives:
1. Component Directives
2. Structural Directives
3. Attribute Directives
Component Directives
Components are the most common of the directives. It contains the details of how the component should be processed, instantiated, and used at runtime. The component comprises meta-data.
Structural Directives
These directives are used to manipulate and change the structure of the DOM elements. Structural directives have a star (*) sign before the directive. Like as,* ngIf, *ngFor, and *ngSwitch directive.
- *ngIf : The *ngIf allows us to Add/Remove DOM Element.
- *ngSwitch : The *ngSwitch will enable us to Add/Remove DOM element. It is same as the switch statement of C#.
- *ngFor : The *ngFor directive is used to repeat a part of HTML template once per each item from an iterable list (Collection).
Attributes Directives
Attribute directives are used to change the look and behavior of the DOM elements. For example: ngClass, ngStyle etc.
- NgClass: The ngClass Directive is used to add or remove CSS classes to an element.
- NgStyle: The ngStyle Directive facilitates you to modify the style of an HTML element using the expression. We can also use the ngStyle Directive to change the style of our HTML element dynamically.
How to Create Custom Directives in Angular ?
Here is the command to create the custom directive in the Angular command line tool –
ng g directive change-color
The above command will generate 2 files, change-color.directive.ts
and change-color.directive.spec.ts
. And in the process, app.module.ts
file is updated as well.
Comments
Post a Comment