Definition of Directives?
Directives are classes that add or modify behavior in the DOM (Document Object Model) elements within the template.

Tip

What is DOM?

Using the DOM, we can dynamically change the value or content of both <p> and <h> tags (or any other HTML elements). You can do this by selecting the element and modifying its properties, such as textContent or innerHTML.

document.getElementById('myPara').textContent = 'New text!';

Purpose of Directives? Directives are used to manipulate the DOM, such as adding/removing elements or changing their appearance.


ngClass Directive

The ngClass directive allows you to add or remove CSS classes dynamically.

  • It is an attribute directive that binds CSS classes to HTML elements based on expressions.

How to Use ngClass

  • 1. String Expression
    You can bind a string directly to ngClass to apply one or more classes:

    <h2 [ngClass]="'myColor myFont'">Test by MSA</h2>
  • 2. Array Expression
    You can use an array to assign multiple classes:

    <h2 [ngClass]="['myColor', 'myFont']">Test by MSA</h2>
  • 3. Object Expression
    You can conditionally apply classes using an object, where the key is the class name and the value is a boolean:

    <h2 [ngClass]="{'myColor': true}">Test by MSA</h2>

Example Using Arrays and Objects

Component (TS)

public myArray = ["myColor", "myWriting"];
public c = new MyClass();
 
constructor() {}
 
ngOnInit(): void {}

Class Definition

class MyClass {
  myColor = true;
  myWriting = true;
}

HTML

<h2 [ngClass]="myArray">Test by MSA</h2>
<h2 [ngClass]="myArray">Test by MSA</h2>

ngClass Without Square Brackets

  • If you use ngClass without square brackets, the expression is directly assigned to the class attribute (no evaluation).

  • Remove the quotes around the expression:

    <h2 ngClass='myColor myFont'>Test by MSA</h2>