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:
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]overNgClass.
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.
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]:
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.NgTemplateOutletrenders a template, optionally with a context object.
Together they let you reuse a piece of markup within one component:
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-flowconverts*ngIf/*ngFor/ngSwitchto the block syntax.
Test yourself
Which kind of directive adds or removes elements from the DOM?
- Attribute directive
- Structural directive
- Pipe
- Service
What does <ng-container> render in the final DOM?
- A <div>
- A <span>
- No element of its own, only its children
- A comment with the template source
With [ngClass]="{ a: true, b: false, c: true }", which classes are applied?
- a b c
- a c
- b
- none