What is a directive class in Angular?

What is Angular?

Angular is a framework developed by Google that composes multiple segments to create web applications. Angular lets you enhance the capabilities of HTMLHyperText Markup Language by providing HTML features in the form of directives.

What is a directive class?

Directives are known as classes that enhance the functionalities of elements in applications built on Angular.

There are numerous types of Angular directives:

  • Attribute directives: Directives that update the functionality or the layout of an element.

  • Components: Directives that have templates.

  • Structural directives: Directives that customize the DOMDocument Object Model layout by deleting or inserting DOM elements.

Built-in attribute directives

These attributes update and respond to the behavior of other attributes, components, and HTML elements.

Some of the most common types are:

  • ngClass
  • ngStyle
  • ngModel

ngClass and an expression

The following code displays the use of ngClass as an expression.


<div [ngClass]="Educative-header"> This is Educative header</div>

ngClass with a method

In this example, setEducativeClasses assigns the functionality of EducativeClasses with an object that removes or adds up additional three classes on the judgment of the true or false state of their additional three components.

EducativeClasses: Record<string, boolean> = {};
setEducativeClasses() {
// these CSS classes are altered on the basis of state
this.EducativeClasses = {
modified: this.isUnchanged,
saveable: !this.canSave,
special: !this.isSpecial
};
}

Inline styles with ngStyle

The following code uses ngStyle to add/alter style across a div.

EducativeStyles: Record < string, string > = { };
setEducativeStyles() {
this.EducativeStyles = {
'font-weight': this.isUnchanged ? 'bold' : 'normal',
'font-style': !this.canSave ? 'italic' : 'normal',
'font-size': this.isSpecial ? '36px' : '12px'
};
}

This example includes the ngStyle property to "EducativeStyles".

<div [ngStyle]="EducativeStyles">
This div is initially bold weight, normal, and extra large (36px).
</div>

Free Resources