TExcelTAD
Home › Angular › Built-in Directives

Built-in Directives

A directive is a class that adds behaviour to an element in a template. Components are actually directives with a template of their own. The other two kinds are:

Kind What it does Examples
Attribute directive Changes the appearance or behaviour of an existing element NgClass, NgStyle, NgModel
Structural directive Adds or removes elements (marked with *) *ngIf, *ngFor, *ngTemplateOutlet

Since Angular introduced @if / @for / @switch, you rarely need the structural directives for everyday conditions and loops, but you will still meet them in existing code, and the attribute directives remain very useful.

NgClass

[ngClass] accepts a string, an array or an object of className: condition pairs. It's handy when several classes depend on different conditions:

angular · try it yourself
import { Component, signal } from '@angular/core';
import { NgClass } from '@angular/common';

@Component({
  selector: 'app-alert',
  imports: [NgClass],
  template: `
    <div class="alert" [ngClass]="{ success: kind() === 'success', error: kind() === 'error', dismissible: closable() }">
      Profile saved successfully.
    </div>
  `,
  styles: `
    .alert { padding: 10px 14px; border-radius: 6px; border: 1px solid #ccc; }
    .success { background: #e7f6ea; border-color: #2e7d32; color: #1b5e20; }
    .error { background: #fdecee; border-color: #dd0031; color: #a00025; }
    .dismissible { padding-right: 36px; }
  `,
})
export class Alert {
  kind = signal<'success' | 'error'>('success');
  closable = signal(true);
}

Tip: Plain [class]="{ success: ok() }" bindings support the same object syntax without importing anything. Many teams now prefer [class.x] and [class] over NgClass.

How an object of classes becomes a class list

The rule NgClass applies is easy to express in TypeScript: keep the keys whose value is truthy.

ts · try it yourself
type ClassInput = string | string[] | Record<string, boolean>;

function toClassList(input: ClassInput): string {
  if (typeof input === 'string') return input;
  if (Array.isArray(input)) return input.join(' ');
  return Object.entries(input)
    .filter(([, on]) => on)
    .map(([cls]) => cls)
    .join(' ');
}

console.log(toClassList('notice success'));
console.log(toClassList(['notice', 'error']));
console.log(toClassList({ notice: true, success: false, error: true, dismissible: true }));
notice success
notice error
notice error dismissible

NgStyle

[ngStyle] sets several inline styles from an object. Keys may include a unit suffix, just like [style.width.px]:

angular · try it yourself
import { Component, signal } from '@angular/core';
import { NgStyle } from '@angular/common';

@Component({
  selector: 'app-swatch',
  imports: [NgStyle],
  template: `
    <div [ngStyle]="{ 'background-color': color(), 'width.px': size(), 'height.px': size() }"></div>
    <code>{{ color() }} · {{ size() }}px</code>
  `,
  styles: `div { border-radius: 8px; margin-bottom: 6px; }`,
})
export class Swatch {
  color = signal('#dd0031');
  size = signal(60);
}

ng-template, ng-container and NgTemplateOutlet

  • <ng-template> defines a chunk of template that is not rendered until something asks for it.
  • <ng-container> is a grouping element that produces no DOM element of its own.
  • NgTemplateOutlet renders a template, optionally with a context object.

Together they let you reuse a piece of markup within one component:

angular · try it yourself
import { Component } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';

@Component({
  selector: 'app-contacts',
  imports: [NgTemplateOutlet],
  template: `
    <ng-template #row let-person let-tag="tag">
      <div>{{ person }} <small>({{ tag }})</small></div>
    </ng-template>

    <h4>Team</h4>
    <ng-container *ngTemplateOutlet="row; context: { $implicit: 'Hoa', tag: 'design' }" />
    <ng-container *ngTemplateOutlet="row; context: { $implicit: 'Lucas', tag: 'backend' }" />
  `,
})
export class Contacts {}

let-person receives the special $implicit value; let-tag="tag" picks a named property from the context.

Legacy structural directives

You will find these in many existing projects. Here is how they map to the new blocks:

Legacy Modern
<p *ngIf="user">…</p> @if (user) { <p>…</p> }
<li *ngFor="let t of tasks; trackBy: byId"> @for (t of tasks; track t.id) { <li> }
<div [ngSwitch]="mode"><p *ngSwitchCase="'a'"> @switch (mode) { @case ('a') { <p> } }

Note: The Angular CLI ships an automatic migration: ng generate @angular/core:control-flow converts *ngIf/*ngFor/ngSwitch to the block syntax.

Test yourself

Which kind of directive adds or removes elements from the DOM?

  1. Attribute directive
  2. Structural directive
  3. Pipe
  4. Service

What does <ng-container> render in the final DOM?

  1. A <div>
  2. A <span>
  3. No element of its own, only its children
  4. A comment with the template source

With [ngClass]="{ a: true, b: false, c: true }", which classes are applied?

  1. a b c
  2. a c
  3. b
  4. none