Directives In Angular
In this article, we will learn about the Angular Directives. The most important features of Angular are Angular Directives. Component, Structural, and Attribute Directives are three sorts of directives that Angular provides in this article. We also take a look at a handful of the most popular Angular directives.
What is Angular Directive
The Angular directive allows us to interact with the DOM. The Directives allow you to change the appearance, behavior, or layout of a DOM element. They assist you in extending HTML.
In Angular, there are three types of directives:
- Component Directive
- Structural directives
- Attribute directives
Component Directive
In Angular, components are special directives. They are the directives that have a template attached to them (view) In this article we learned how to create angular Components.
Structural Directives
By adding and removing DOM elements, structural directives can alter the DOM layout. The Asterix emblem appears before all structural directives.
Commonly used structural directives
ngFor
The ngFor structural directive is an Angular directive that repeats a part of the HTML template once for each item in an iterable list (Collection). In AngularJS, ngFor is equivalent to ngRepeat.
Example of ngFor
<tr *ngFor="let customer of customers;"> <td>{{customer.customerNo}}</td> <td>{{customer.name}}</td> <td>{{customer.address}}</td> <td>{{customer.city}}</td> <td>{{customer.state}}</td> </tr>
ngSwitch
<div [ngSwitch]="Switch_Expression"> <div *ngSwitchCase="MatchExpression1”> First Template</div> <div *ngSwitchCase="MatchExpression2">Second template</div> <div *ngSwitchCase="MatchExpression3">Third Template</div> <div *ngSwitchCase="MatchExpression4">Third Template</div> <div *ngSwitchDefault?>Default Template</div> </div>
ngIf
<div *ngIf="condition"> This is shown if condition is true </div>
Attribute Directives
Commonly used Attribute directives
ngModel
ngClass
<div [ngClass]="'first second'">...</div>
ngStyle
<div [ngStyle]="{'color': 'blue', 'font-size': '24px', 'font-weight': 'bold'}">
some text
</div>