What is directive in angular and types of directive in angular

 

directive

Angular directive is one of core building blocks of angular which provides additional behavior to elements in your application. 

We can attach extra attributes to the markup language parts (elements) which may helps you manipulate the looks of web page. 

c

funny

You know , the components are the building blocks of an angular applications because of directives, components are nothing more than a directive with a templet.

Components have their own templets whereas angular directive has directions to vary visual illustration and rendering the template. Angular 12 is released, grasp what is new in it 

Type of directives in angular

There are three types of directives in angular. 

example
  • Components directive - directive with template
  • Attribute directive - change the appearance and behavior of DOM element
  • Structural directive - change layout by adding or removing DOM element


Component directive

Component directives are most commonly used directives in angular that is why components are one of core building blocks in angular.
As components directive has their own template and attributes so that they can easy be managed changing the appearance of DOM elements. 
It is mandatory to import declare the component directive in module.

errorMessage.directive.ts
import {Directive, ElementRef} from '@angular/core';

@Directive({
    selector:'[error-message]'
})

export class ErrorMessageDirective{
    constructor(elr:ElementRef){
        elr.nativeElement.style.background='red';
    }
}
app.component.html
<p error-message>
   Hi , my color was changed by angular directive
</p>
Do not forget to declare error-message directive in app.module.ts

example

Results

example

Like the above example, we made a custom directive to apply red background for errors in angular application and then we can simply put the directive in DOM elements which element to want with red background.

Attribute Directive

Attribute directive are used to change the appearance and the behavior of DOM element where Angular provides built in attribute directives like NgStyle NgClass ,
Where we can change the styling of DOM element dynamically basis of some conditions.

Simply Attribute directives are used for conditional styling in angular with 
  • ngStyle directive
  • ngClass directive

NgStyle Directive

ngstyle directive is used to style HTML elements where we give some condition into ngStyle so it can then apply desired changes.  

Example:
app.component.html
<div [ngStyle]="{'border':isConditionMatch ? '4px solid green' : '5px solid red' }"> 
  ngStyle Example
<div>
app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular 6';
  isConditionMatch = true;
}
Result:
directive-example

In the above example we set a border on text "ngstyle example" conditionally using ngStyle directive.
"isConditionMatch" is set to true in app.component.ts and in the HTML file we used ternary operator  to set the border dynamically in NgStyle directive.

NgClass Directive

Ngclass directive is second attribute directive in angular which is used to change the behavior and appearance of a DOM element conditionally. 

Using ngClass directive we can set classes to a HTML element conditionally so that it can change the appearance soon as it matches with the condition.

In the above example we set border using ngStyle and that can also be implemented using ngClass. let's see how it works

app.component.css
.custom-class {
  border: 3px solid green
}
app.component.ts
<div [ngClass]="isConditionMatch ? 'custom-class' : '' ">ngStyle Example<div>

Structural Directive

As the name define itself , Structural directives are used to change the structure of a DOM element by adding or removing elements.it can easiy be identify by '*'  like *ngIf etc.
we have four built in and commonly used structural directives in angular.
  1. ngIf
  2. ngFor
  3. ngSwitch
  4. ngIf-else

1. ngIf

ngIf directive is used to show or hide a DOM element in angular by passing an expression value assigned to ngIf. Expression value could be either true or false.
Example:

import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: 
  `<h1 *ngIf="1 < 2" >tag 1</h1>
  <h1 *ngIf="false" >tag 2</h1>
  <h1 *ngIf="property" >property</h1>
  <h1 *ngIf="nullValue" >null</h1>`,
})
export class AppComponent  {
  property = true;
  nullValue = null;
 }
Output:
angular
ngIf directive

2. NgFor

ngFor directives are used to loop DOM elements, we pass an array object so that ngFor can detect the length of array object to render DOM elements.

 ngFor can used async using rxjs, that may help you render DOM elements asynchronously.
Example

app.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'ngfor-grouped-example',
  templateUrl: './grouped-example.component.html',
  styleUrls: ['./grouped-example.component.css']
})
export class GroupedExampleComponent  {

   peopleByCountry: any[] = [
    {
      'country': 'UK',
      'people': [
        {
          "name": "Douglas  Pace"
        },
        {
          "name": "Mcleod  Mueller"
        },
      ]
    },
    {
      'country': 'US',
      'people': [
        {
          "name": "Day  Meyers"
        },
        {
          "name": "Aguirre  Ellis"
        },
        {
          "name": "Cook  Tyson"
        }
      ]
    }
  ];
}
app.component.html
<ul *ngFor="let group of peopleByCountry">
  <li>{{ group.country }}</li>
  <ul>
    <li *ngFor="let person of group.people">
      {{ person.name }}
    </li>
  </ul>
</ul>
Output
angular-directive
ngFor directive

3. ngSwitch

ngSwitch directive is used to hide or show DOM elements by expression inside *ngSwitchCase 
where it matches the expression by the value you give to it we can have multiple cases to show or hide HTML elements and if there is no matching expression then ngSwitchDefault comes to show the elements.
Example:
import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  positions:Array<Object> = [
    {
      id: 101,
      name: 'CEO'
    },
    {
      id: 102,
      name: 'CFO'
    },
    {
      id: 103,
      name: 'CTO'
    },
    {
      id: 104,
      name: 'CMO'
    }
  ]
}
Output four

 

4. ngIf-else

ngIfElse is amazing directive where we can have both cases, we can show matched expression value Html element as well as the else case to show any other element.

But we need to define the element so that if can be render after matching the expression.

<input [(ngModel)]="showContent" type="checkbox"/> Show My Secret Message
<hr />
<div *ngIf="showContent; else message">
  Hello Angular 12!
</div>
<ng-template #message>
  Click the checkbox above to read the secret message!
</ng-template>
Ouput:
result

Angular 12 just released, know what's new in it 

Summary

In this article, we have focused on angular directive , we have covered three types of directives in angular where ngClass and ngStyle may have more than one expression to provide appearance and behavior to DOM elements.
If you want some custom features then angular provides us a way to do that by custom directives where we can have our own logic to change the behavior of HTML elements.

If we talk about ngif directive then we pass match multiple expressions at once so that the DOM element can be rendered matching the conditions.

If you enjoyed the article , considering following , thanks!
 

No comments:

Powered by Blogger.