in Angular by
What are directives in Angular?

1 Answer

0 votes
A directive is a class in Angular that is declared with a @Directive decorator.

Every directive has its own behaviour and can be imported into various components of an application.

When to use a directive?

Consider an application, where multiple components need to have similar functionalities. The norm thing to do is by adding this functionality individually to every component but, this task is tedious to perform. In such a situation, one can create a directive having the required functionality and then, import the directive to components which require this functionality.

Types of directives

Component directives

These form the main class in directives. Instead of @Directive decorator we use @Component decorator to declare these directives. These directives have a view, a stylesheet and a selector property.

Structural directives

These directives are generally used to manipulate DOM elements.

Every structural directive has a ‘ * ’ sign before them.

We can apply these directives to any DOM element.

Let’s see some built-in structural directives in action:


      <div *ngIf="isReady" class="display_name">



      <div class="details" *ngFor="let x of details" >


          <p> {{x.address}}</p>





In the above example, we can *ngIf and *ngFor directives being used.

*ngIf is used to check a boolean value and if it’s truthy,the div element will be displayed.

*ngFor is used to iterate over a list and display each item of the list.

Attribute Directives

These directives are used to change the look and behaviour of a DOM element. Let’s understand attribute directives by creating one:

How to create a custom directive?

We’re going to create an attribute directive:

In the command terminal, navigate to the directory of the angular app and type the following command to generate a directive:

ng g directive blueBackground

The following directive will be generated. Manipulate the directive to look like this:


      import { Directive, ElementRef } from '@angular/core';


       selector: '[appBlueBackground]'


      export class BlueBackgroundDirective {

       constructor(el:ElementRef) {
 = "blue";





Now we can apply the above directive to any DOM element:


      <p appBlueBackground>Hello World!</p>
Click here to read more about Angular JS
Click here to read more about Insurance

Related questions

0 votes
asked Jan 15, 2020 in Angular by rahuljain1
+1 vote
asked Jan 15, 2020 in Angular by rahuljain1
0 votes
asked Jan 15, 2020 in Angular by rahuljain1
0 votes
asked Jan 6, 2020 in Angular by sharadyadav1986
0 votes
asked Jan 15, 2020 in Angular by rahuljain1