Angular

Fundamentals of Angular Directives - Three Types of Directives in Angular

Attribute Directives

Attribute directives enable Angular developers to define an attribute that when added to an element change the appearance of the element or enhance the functionality of the element.

Some examples of attribute directives include: - Highlighting the text of an element - Focusing on an input when a specific action occurs - Showing a definition for a word when the user hovers or clicks on an element - Hiding and showing a modal when a button is clicked

Attribute directives have access to the ElementRef of the element where the attribute has been applied. Using the ElementRef instance we can get access to the nativeElement in the DOM. Keep in mind that Angular does not always execute within the context of a browser, so be sure to check if the nativeElement is defined.

Structural Directives

Structural directives enable Angular developers to add, edit and remove elements in the DOM. A good example of this is the built-in ngFor directive. Structural directives all begin with an asterisk to denote that the directive modifies the structure of the DOM.

Note that when adding and removing elements using structural directives like NgFor and NgIf that the DOM is indeed mutated. What I mean by this is that when an element is removed it not simply hidden, it is actually removed from the DOM. The impact of this is important to understand. If you remove an element that is a directive or contains multiple directives, the directives are torn down and destroyed. Conversely, when you add an element that contains one or more directives they are created and initialized at runtime.

Component (Directives)

Often time we refer to component directives simple as "components".

Components are special directives because they contain a template that is rendered in your application. This enables you to define directives that contain templates using a rich HTML-like syntax. This takes directives a step further in that you are not just modifying the DOM via APIs, rather, you are inserting HTML directly into the DOM.