Skip to main content

Built-in Directives

Angular offers a wide variety of built-in directives that can help you manipulate the DOM (Document Object Model) in various ways. These built-in directives are categorized into three main types:

  1. Attribute Directives: These directives change the appearance or behavior of a DOM element.
  2. Structural Directives: These directives manipulate the DOM layout by adding, removing, or replacing elements in DOM.
  3. Component Directives: These directives are basically custom components, which are a combination of a template and a class.

Let's take a deep dive into each type to understand them better.

Attribute Directives

Attribute directives are used to change the behavior, style, or appearance of an element. Some of the most commonly used attribute directives are:

  • NgStyle: This directive allows you to set CSS styles on an HTML element dynamically.
<div [ngStyle]="{color: 'red'}">This text will be in red color.</div>
  • NgClass: This directive allows you to dynamically add or remove CSS classes on an HTML element.
<div [ngClass]="{'active': isActive}">This div will have 'active' class if isActive is true.</div>

Structural Directives

Structural directives are used to change the DOM layout by adding, removing, or replacing elements. Angular defines several structural directives, including:

  • NgFor: This directive is used for rendering a list of items.
<div *ngFor="let item of items">{{ item }}</div>
  • NgIf: This directive is used to conditionally add or remove an element from the DOM.
<div *ngIf="showDiv">This div will show if showDiv is true.</div>
  • NgSwitch: This directive is used to add or remove DOM sub-trees.
<div [ngSwitch]="value">
<p *ngSwitchCase="'A'">Value is A</p>
<p *ngSwitchCase="'B'">Value is B</p>
<p *ngSwitchDefault>Value is neither A nor B</p>
</div>

Component Directives

Component directives are essentially custom components. You can define your own components with a combination of a template and a class. Here's an example of a basic component directive:

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

@Component({
selector: 'my-component',
template: `<h2>Welcome to My Component!</h2>`
})
export class MyComponent {
// Your class logic goes here
}

In the above example, 'my-component' is the selector for the custom component. You can use this component in your HTML like this:

<my-component></my-component>

This will render "Welcome to My Component!" text on the page.

In conclusion, directives in Angular provide a powerful way to work with and manipulate the DOM. Whether it's changing the appearance of an element, manipulating the DOM layout, or creating custom components, Angular's built-in directives have got you covered. The key is to understand which directive to use in which scenario and how to apply them correctly.