Loading

Introduction to Angular's Directive

Introduction to Angular's Directive

Angular Directives

We can manipulate the DOM with the help of Angular Directives. We can change appearance, behaviour or layout of DOM element. it helps to extend HTML.

In Angular, there are three types of Angular Directives

  1. Component Directive
  2. Structural Directive
  3. Attribute Directive

Component Directive:- This form the main class and declared by @component Example

@Component({ 
  selector: 'app-root', 
  templateUrl: './app.component.html', 
  styleUrls: ['./app.component.css'] 
}) 

Structural Directive:- You can add or remove DOM elements from DOM layouts using component directive. All structural directive are preceded by * symbol. such as *ngIF, *ngFor

Example of *ngIf

<div *ngIf=""article">
<h2><a routerLink="/article/{{ article.id }}" routerLinkActive="active"> {{ article.title }}</a></h2>
</div>

Example of *ngFor

<div *ngFor="let article of articles">
    <h3> {{ article.category.name }}</h3>
    <h2><a routerLink="/article/{{ article.id }}" routerLinkActive="active"> {{ article.title }}</a></h2>
</div>

Example of *ngSwitch

<div [ngSwitch] ="switchExpression">
   <div *ngSwitchCase="matchExpression1">Expression 1</div>
   <div *ngSwitchCase="matchExpression2">Expression 2</div>
   <div *ngSwitchCase="matchExpression3">Expression 3</div>
   <div *ngSwitchDefault?>Default</div>
</div>

Attribute Directive;- This can change the behaviour or appearance of an element.

ngModel:- ngModel directive is used for two-way data binding

<div class="form-group">
    <input class="form-control form-control-lg" type="text" placeholder="Type name" [(ngModel)]="name">
</div>

ngClass:- It is used to add or remove the CSS classes from an HTML element.

<div class="statusIcon tooltipsLink" [ngClass]="{
    'icon-tick': status == 'Completed',
    'icon-Delay':  status == 'Delayed',
    'orangeTick':  status == 'Delayed Scan',
    'icon-Missed-progress':  status == 'Missed',
    'icon-Hold-Off':  status == 'HoldOff',
    'icon-blank':  status == 'Pending' }">
    <!--icon-->
    <span class="path1"></span>
    <span class="path2"></span>
    <span class="path3"></span>
</div>

ngStyle:- It is used to change the multiple style properties of HTML elements.

<div [ngStyle]="{'color':'red','font-weight':'bold'}>Sample Text</div>

Related Articles