A quick guide to angular directive and List of directives in angular

A quick guide to angular directive and List of directives in angular


Angular directive is one of core building blocks of angular which provides additional behavior to elements in your application. we can attach additional attributes to the HTML elements which can helps you manipulate the appearance of web page HTML elements.

With directives you can extend the power of HTML web page by applying new syntax. A directive is provides same features of a component but except it does not have templates. 

No alt text provided for this image

You know , Components are the building blocks of angular applications because of directives? 

An angular component is nothing more than a directive with a template, components have their own templates but directives do not 

But angular directive has instructions to change visual representation and rendering the template.

Type of directives in angular

There are three types of directives in angular. 

  • 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 decorator 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.tsimport {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

Results

No alt text provided for this image

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.tsimport { 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:

No alt text provided for this image

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:

No alt text provided for this image

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.tsimport { 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:

No alt text provided for this image

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:

No alt text provided for this image

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 follow the site , thanks!

Original post can be found on https://www.akashminds.com/

Dinesh Thorat

Driving Growth with Sales & Marketing.

10 个月

You can also check out my blog for more in detail topic overview:- https://www.angularminds.com/blog/directives-in-angular

回复

要查看或添加评论,请登录

Akash Chauhan的更多文章

社区洞察

其他会员也浏览了