Directives in Angular 7 are Typescript class which is declared with decorator @Directive. These are the Document Object Model (DOM) instruction sets, which decide how logic implementation can be done. Angular directives can be classified into three types:
Component Directives: It forms the main class and is declared by @Component. It contains the details on component processing, instantiated and usage at run time. Example: It contains certain parameters some of them are shown in this example.
javascript
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
There are three parameters discussed below:
Selector: Tells the template tag which specifies the beginning and end of the component.
templateURL: Consists of the template used for the component.
styleUrls: It is of array type which consists of all the style format files used for the template.
Structural Directives: Structure directives manipulate the DOM elements. These directives have a * sign before the directive. For example, *ngIf and *ngFor. Example: Let’s look the implementation of *ng-if-else and *ng-for. Using them, we classify weekdays and weekends. Component file:
javascript
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
Weekdays:Array =[
'Sunday', 'Monday', 'Tuesday',
'Wednesday', 'Thursday', 'Friday', 'Saturday']
}
Template file:
html
<div*ngFor="let day of Weekdays">
<ng-container*ngIf=
"(day == 'Saturday' || day == 'Sunday'); else elseTemplate">
<h1>{{day}} is a weekend</h1>
</ng-container>
<ng-template#elseTemplate>
<h1>{{day}} is not a weekend</h1>
</ng-template>
</div>
Output:
Attribute Directives: Attribute directives are used to change the look and behavior of the DOM element. It provides the facility to create our own directive. Example: This example describes how to make our own directive. Write command as follows:
ng g directive
Directive:
javascript
import { Directive, ElementRef, OnInit } from '@angular/core';
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
This article is being improved by another user right now. You can suggest the changes for now and it will be under the article’s discussion tab.
You will be notified via email once the article is available for improvement.
Thank you for your valuable feedback!
Please Login to comment...