DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

kamran
kamran

Posted on • Updated on

Give magical powers to your DOM in AngularΒ JS

One of my mentees asked me why we use angular when the same thing can be built using html,so i explained to him about performance, maintenance and code organization but he was not convinced. So I have to explain the magical powers of angular to him. I told him that angular is a wizard who can give magical powers to any element.

Image description

To give new power to any element we need magic spells which we call as "Directives". Basically Directives are classes that add new behavior or modify the existing behavior to the elements in the template.

So you can add two types of magical power or behavior to an element, one is attribute directive in which you can modify attribute behavior of an element like you can modify style attribute using ngSTyle where you can put complex style in the element.There are many inbuilt attribute directives available like ngClass or ngModel.

<div [ngStyle]="{'background-image': 'url(' + valueΒ ? imageΒ : otherImage + ')'}"></div>
Enter fullscreen mode Exit fullscreen mode

The other kind of magical power or behavior is Structural directive, where you can change the whole behavior of an element altogether, like you can set visibility of an element using ngIf directive or you can show list of an element using ngFor.

<div *ngIf="condition">Content to render when condition is true.</div>
Enter fullscreen mode Exit fullscreen mode

These two directive i have explained practically in my YT video series as well, you can check that too.
You can also create your own spell, means you can create your own directive as well
Simplest custom directive can be:

import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
   constructor(private eleRef: ElementRef) {
      eleRef.nativeElement.style.background = 'red';
   }
}
Enter fullscreen mode Exit fullscreen mode

This directive simply update the color of element to red but you can have an idea form this how to create a custom directive.

This brief blog gives you idea about what is directives in Angular, Happy Koding everyone!!!

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.