The Angular Directives — A Brief Intro

Yathusanan Yokarajah
3 min readSep 4, 2020

--

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

  1. Directives
  2. Structural directives
  3. Attribute directives
  4. Component directives
  5. Custom Attribute directives
  6. Host listener
  7. 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

  1. Structural directives
  2. Attribute directives
  3. 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.

using a structural directive (*ngFor)

The followings are the structural directives in Angular. You can get more information by looking at the documentation.

  1. ngFor
  2. ngIf
  3. 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.

using attribute directive (in the HTML template)
we defined the style in the ts file

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.

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

  1. Structural directives
  2. Attribute directives
  3. Component directives
  4. Custom Attribute directives
  5. Host listener
  6. 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.

--

--