Tuesday, March 24, 2020

Angular Directives


Directives in Angular are JavaScript class which is declared as @directive. These are the Document Object Model (DOM) instruction sets, which decide how logic implementation can be done. Directives are actually markers on a DOM element that tell Angular to attach a specified behavior to that DOM element or even transform the DOM element and its children. In short, it extends the HTML.

Most of the directives in Angular are starting with ng- where ng stands for Angular. Angular includes various built-in directives. Angular directives can be classified into three types:
·       Component Directives
·       Structural Directives
·       Attribute Directives

Component Directives
Component directives are used in main class. They contain the detail of how the component should be processed, instantiated and used at runtime. This is the special directive which is always present in an Angular application. Each of our HTML page associated with this directive.
Component Directive is nothing but a class with @Component decorator function. As we know Angular application contains at least one component called “AppComponent” which present inside “App-compoennt.ts” file. In this file, we see @Component (a decorator function) which is used to create a component directive with the help of selector.

Example of Component Directive

Create a new project, called “myapp” with the following commands :
ng new myapp
Now, go “app.component.ts” file, we can see the below code,
import { Component } from '@angular/core';  
  
@Component({  
 selector: 'app-root',  
 templateUrl: './app.component.html',  
 styleUrls: ['./app.component.css']  
})  
export class AppComponent {  
 title = 'app';  
}  


In the above line of code, Angular used @Component, a decorator function to create a template directive called “app-root”. We can use this directive on index page like this :
<app-root></app-root>  



Attribute Directives 

Attribute directives are used to change the look and behavior of the DOM elements. For example: ngModel, ngClass, ngStyle etc. The ng-model directive is used for two-way data binding in Angular. It binds <input>, <select> or <textarea> elements to a specified property on the $scope object. So, the value of the element will be the value of a property and vica-versa.

Example of ng-model Directive

Step-1: Create a new component called Cricketer with the following command:

ng g c Cricketer

Step-2: Add the following code in Cricketer.component.ts:

import { ComponentOnInit } from "@angular/core";

@Component({
  selector: "app-cricketer",
  templateUrl: "./cricketer.component.html",
  styleUrls: ["./cricketer.component.css"]
})
export class CricketerComponent implements OnInit {

  inputPlayer = null;

  constructor() {}

  ngOnInit() {}
}

Step-3: Add the following code in Cricketer.component.html:

<div class="container">
  <div class="row">
    <div class="col-md-4 col-md-offset-4">
      <ul class="list-group">
        <li class="list-group-item">
          <input type="text" [(ngModel)]="inputPlayer" />
          <br /><br />
        </li>
        <li class="list-group-item">
          {{ inputPlayer }}
        </li>
      </ul>
    </div>
  </div>
</div>

Explanation: Here [(ngModel)]="inputPlayer" provides two-way data binding using ngModel Attribute Directive.

Code Output:



Structural Directives

Structural directives start with a * sign. These directives are used to manipulate and change the structure of the DOM elements. For example, *ngIf and *ngFor.

Example of Structural Directive having *ngIf and ngFor

Step-1: In Cricketer.component.html update it with following code:

<div class="container">
  <div class="row">
    <div class="col-md-4 col-md-offset-4">
      <ul class="list-group">
        <li class="list-group-item" *ngFor="let player of players">
          {{ player }}
        </li>

        <li class="list-group-item">
          <button class="btn btn-info" (click)="Addmore()">
            Add More
          </button>
        </li>

        <li class="list-group-item">
        {{ inputPlayer }}
      </li>

        <li class="list-group-item" *ngIf="Adding">
          <input type="text" [(ngModel)]="inputPlayer" />
          <br /><br />
          <button
            (click)="addPlayer()"
            class="btn btn-danger"
            [disabled]="!inputPlayer" >
            Add Player
          </button>
        </li>
      </ul>
    </div>
  </div>
</div>

Step-2: In Cricketer.component.ts update it with following code:

import { ComponentOnInit } from "@angular/core";

@Component({
  selector: "app-cricketer",
  templateUrl: "./cricketer.component.html",
  styleUrls: ["./cricketer.component.css"]
})
export class CricketerComponent implements OnInit {
  players = ["sachin""kohli""Ms Doni""Rahul"];

  inputPlayer = null;
  Adding = false;

  Addmore() {
    this.Adding = !this.Adding;
  }
  addPlayer() {
    this.players.push(this.inputPlayer);

    this.inputPlayer = null;

    this.Adding = false;
  }

  constructor() {}

  ngOnInit() {}
}

Explanation: Here *ngFor="let player of players" ngFor is used to print repeatedly the array object players = ['sachin''kohli''Ms Doni''Rahul'] and *ngIf="Adding" is used toggle out Add Player Button when we are adding More Player in the application. Add Player button is initially disable using property binding [disabled]="!inputPlayer".

Code Output: