Skip to content
Angular

Built-in Directives

Use *ngIf, *ngFor, ngClass, and ngStyle to shape the DOM.

By EZ4Code Team
directivesngIfngFor

Code

import { Component } from "@angular/core";
import { NgIf, NgFor, NgClass, NgStyle } from "@angular/common";

@Component({
  selector: "app-directives",
  standalone: true,
  imports: [NgIf, NgFor, NgClass, NgStyle],
  template: `
    <p *ngIf="show; else loading">Visible</p>
    <ng-template #loading>Loading...</ng-template>
    <li *ngFor="let item of items; let i = index">
      {{ i + 1 }}: {{ item }}
    </li>
    <div [ngClass]="{ active: isActive, disabled: !isActive }">Class</div>
    <div [ngStyle]="{ color: isActive ? 'green' : 'red' }">Style</div>
  `
})
export class DirectivesComponent {
  show = true;
  items = ["a", "b", "c"];
  isActive = true;
}

Explanation

Structural directives reshape the DOM: *ngIf conditionally renders and *ngFor loops over collections. Attribute directives alter element appearance via [ngClass] and [ngStyle]. The asterisk is syntactic sugar that unwraps into ng-template elements.

More Angular Snippets