Interview Questions

1. What are the different types of directives in Angular?

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 the @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 examples 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.

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

          {{name}}  

 </div>  

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

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

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

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

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

</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:

  • ng g directive yellowBackground   

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

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

@Directive({  

 selector: '[appYellowBackground]'  

})  

export class YellowBackgroundDirective {  

 constructor(el:ElementRef) {  

   el.nativeElement.style.backgroundColor = "yellow";  

 }  

}  

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

<p appYellowBackground>Hello JavaTpoint</p>  

By Md Riyazuddin 2 0
Is this helpful? Yes No

Submit an interview question

Submitted questions and answers are subject to review and editing, and may or may not be selected for posting, at the sole discretion of w3Sniff.

Get Started

Comments

Leave a Comment


Check out more interview questions

Based on your skills

MS SQL Server

97974 1720 4 860

Angular

2781 92 0 46

Wordpress

2156 72 0 36
AD Ad-Free