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