What are Angular Directives?
Directives are nothing but the classes that add additional behavior to elements in your Angular applications. It is declared with decorator @Directive.
There are three types of directives –
- Component Directive : It must be declared in Angular Modules in the same manner as components. This type of directive is the most common directive type. A component, rather than adding/modifying behavior, actually creates its own view (hierarchy of DOM elements) with attached behavior. Component directive is used to specify the HTML templates. It has structure design and the working pattern of how the component should be processed, instantiated and used at runtime.
demo-directive.ts:
app.component.html :
In the above example, there is a class called ChangeTextDirective and a constructor, which takes the element of type ElementRef, which is mandatory. The element has all the details to which the Change Directive is applied.
2. Structural Directive : These are responsible for changing the structure of the DOM. They shape or reshape the DOM’s structure, typically by adding, removing, and manipulating the host elements to which they are attached. The Structural Directive’s name always starts with an asterisk(*) prefix.
Most commonly used structural directives are –
- NgIf : conditionally creates or disposes of sub-views from the template.
- NgFor : repeat a node for each item in a list.
- NgSwitch : a set of directives that switch among alternative views.
Will see NgIf, NgFor & NgSwitch in details in upcoming chapter.
3. Attribute Directives: It manipulate the DOM by changing its behavior and appearance. It is u to apply conditional style to elements, show or hide elements or dynamically change the behavior of a component according to a changing property.
Most commonly used attribute directives are –
- NgStyle : used to change the styling of any DOM element on the basis of some condition.
- NgClass : Adds and removes CSS classes on an HTML element.
Conclusion : This is the short description about the angular built in directives. In upcoming chapters will see these in details and look into custom directive as well.