Angular Directives Tutorial

Angular Directives Tutorial

<strong>In this post, we go over three popular directive in Angular and show you how to implement them in your code.</strong>

In this post, we go over three popular directive in Angular and show you how to implement them in your code.

A directive is an add-on or an extension to Angular features, used for optimizing your reusable code.

There are three types of directives in Angular (component, attribute, and structural).

Component Directives

A component is a directive with a template. Basically, whatever we do in Angular is a component. It is a reusable part of the whole application.

Here is an example of a simple animation component that rotates the div by 180 degrees when clicked.

Template:

<div (click)="animateDiv(animatediv)" #animatediv class="animateDiv">CLICK ME</div>

TS file:

import { Component, OnInit } from '@angular/core';

@Component({

  selector: 'app-animation',

  templateUrl: './animation.component.html',

  styleUrls: ['./animation.component.css']

})

export class AnimationComponent implements OnInit {

  constructor() { }

public animateDiv(receivedObj){

 receivedObj.style.;

  }

}

Attribute Directives

An attribute directive changes the way a component, element, or directive looks. Attribute directives are used to give a better look and feel to our element. Some of the commonly used attribute directives in Angular are: ngStylengSwitchngModelngClass.

Below is an example of a simple component showing how to use the ngStyle irectived. It assigns the background color as blue if the item is a fruit and green if it is a vegetable.

<ul *ngFor="let item of items">
  <li class="item" [ngStyle]="{'backgroundColor':getBgColor(item.type)}" > 
    {{ item.name } 
  </li>
</ul>
export class ItemsComponent {

  public items = [

    {id:1,name:'APPLE',type:'fruit'},

    {id:1,name:'TURNIP',type:'vegetable'},

    {id:1,name:'ORANGE',type:'fruit'}

  ];

  public getBgColor(type){

    if(type == 'fruit'){

      return 'blue';

    }else{

      return 'green';

    }

  }

}

Structural Directives

As the name suggests, a structural directive changes the structure of a component, element, or directive. Basically, it is used to manipulate the DOM. Some of the commonly used structural directives in Angular are ngIf and ngFor.

Below is a simple component showing the usage of the ngIf directive. This component toggles the div on the click of the button.

Template:

<button (click)>TOGGLE</button>

<div class="showDiv" *>I AM VISIBLE</div>

TS file:

export class ToggleComponent {

public showDiv:boolean = true; 

public toggleDiv(){

  this.showDiv = !this.showDiv;

}

}

Building Custom Directives

We can also create custom directives based on our requirements and use them throughout the application.

Example

Template:

<p appPaintGreen>I AM A GREEN PARAGRAPH</p>

TS File:

import { Directive, ElementRef } from '@angular/core';

@Directive({

  selector: '[appPaintGreen]'

})

export class PaintGreenDirective {

  constructor(private el:ElementRef) {

    // el here contains the object in which you are using this directive

    el.nativeElement.style.backgroundColor = 'green';

    el.nativeElement.;

  }

}

Conclusion

Directives are basically custom elements that give some extra capability to an element. They can be used based to make our components flexible in both appearance and functionality.

Originally published by Mamatamayee parida at https://dzone.com

Learn More

☞ Angular 7 (formerly Angular 2) - The Complete Guide

☞ Learn and Understand AngularJS

☞ Angular Crash Course for Busy Developers

☞ The Complete Angular Course: Beginner to Advanced

☞ Angular (Angular 2+) & NodeJS - The MEAN Stack Guide

☞ Become a JavaScript developer - Learn (React, Node,Angular)

☞ Angular (Full App) with Angular Material, Angularfire & NgRx

☞ The Web Developer Bootcamp

angular

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Install Angular - Angular Environment Setup Process

Install Angular in easy step by step process. Firstly Install Node.js & npm, then Install Angular CLI, Create workspace and Deploy your App.

Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular. Angular is a Typesc

Angular Sass: How To Use Sass In Angular 9 Tutorial

Sass in Angular is an extension of CSS that allows you to use things like variables, nested rules, inline imports. Angular supports Sass, CSS, and Less.

How to Upgrade Angular 8 To Angular 9

Angular is currently the most popular JavaScript framework and is used by several expert developers when developing single-page applications or powerful web apps. It has become quite crucial for the developers of Angular to add more features to the framework and fix the bugs . Let's learn how to upgrade Angular 8 to Angular 9 using CLI.

Visualizing data with NGX-Charts in Angular

Data Science, Data Analytics, Big Data, these are the buzz words of today's world. A huge amount of data is being generated and analyzed every day. So communica