0 votes
in Angular by
What are the different types of directives in Angular?

1 Answer

0 votes
by

There are mainly three types of directives in Angular:

Component Directives: The component directives are used to form the main class in directives. To declare these directives, we have to use the @Component decorator instead of @Directive decorator. These directives have a view, a stylesheet and a selector property.

Structural directives: These directives are generally used to manipulate DOM elements. The structural directive has a ' * ' sign before them. We can apply these directives to any DOM element.

Following are some example of built-in structural directives:

*ngIf Structural Directive: *ngIf is used to check a Boolean value and if it's truthy, the div element will be displayed.

  1. <div *ngIf="isReady" class="display_name">  
  2.           {{name}}  
  3.       </div>  

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

  1. <div class="details" *ngFor="let x of details" >  
  2.     <p>{{x.name}}</p>  
  3.     <p> {{x.address}}</p>  
  4.     <p>{{x.age}}</p>  
  5. </div>  

Attribute Directives: The attribute directives are used to change the look and behavior of a DOM element. Let's create an attribute directive to understand it well:

This is how we can create a custom directive:

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

  1. ng g directive yellowBackground   

This will generate the following directive. Manipulate the directive to look like this:

  1. import { Directive, ElementRef } from '@angular/core';  
  2. @Directive({  
  3.  selector: '[appYellowBackground]'  
  4. })  
  5. export class YellowBackgroundDirective {  
  6.  constructor(el:ElementRef) {  
  7.    el.nativeElement.style.backgroundColor = "yellow";  
  8.  }  
  9. }  

Now, you can easily apply the above directive to any DOM element:

  1. <p appYellowBackground>Hello JavaTpoint</p>  

Related questions

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