The Angular Directives — A Brief Intro
Introduction
When you want to manipulate the DOM(Document Object Model) in your Angular application, you really need to know about Angular Directives. This article will give you a brief introduction about the followings
- Directives
- Structural directives
- Attribute directives
- Component directives
- Custom Attribute directives
- Host listener
- Host binding
Overview
What are directives? And, why do we need them?
Angular directives are used to manipulate the DOM Element. What is Manipulating the DOM element? Let’s say you wanna implement a feature that only shows the input field when clicking on a button. This is where the directive is on the action.
There are three kinds of directives in Angular
- Structural directives
- Attribute directives
- Component directives
Structural Directives
The structural directive will look like a usual HTML attribute but it has an asterisk * sign before that directive. It affects the whole area in the DOM by adding or removing the element.
The following code snippet shows one of a structural directive.
The followings are the structural directives in Angular. You can get more information by looking at the documentation.
- ngFor
- ngIf
- ngSwitch
Attribute directives
The Attribute directives change the appearance of a DOM element. They look like a usual HTML element. They only affect the element they are added to.
When you want to change the attribute of an HTML element (font color, font style, and etc) you can do that with these directives.
For example, You have a paragraph on your browser and you need to change the font style of that paragraph. So here you can do that with Attribute directives.
Component Directive
Angular application has lots of components. The component directive is a class with a @component decorator. This decorator (@Component) used to create a component directive.
Custom Attribute Directives
We can also create our own custom directive by decorating the class with @Directive decorator.
Host Listener
When we need to react to some events that occurring on the element that the directive sits on, we can use the Host listener decorator.
Host Binding
With host binding, we can supply configuration metadata.
Takeaways
- Structural directives
- Attribute directives
- Component directives
- Custom Attribute directives
- Host listener
- Host binding
Thank you
Thank you very much for spending your time. I hope this article will give you a brief idea about Angular directives.