Skip to the workspace
Pebellslearn by building
Templates and Directives  ›  Lesson

Attribute Directives

Attribute Directives 12 minAttribute directives change how an existing element looks or behaves without adding or removing it, as NgClass, NgStyle and NgModel do.

angular / Attribute Directives

Explore each scene at your own pace.

01 · The rule

The rule

Attribute Directives

A thirsty plant's card should turn amber, a sun-loving plant's card should show a sun icon border, and a card being dragged should fade. None of this adds or removes a card. It changes an element that is already there, which is exactly what attribute directives are for.

The rule

Attribute directives change an element; structural ones change the page.

An attribute directive is written like an HTML attribute and alters the look or behaviour of its host element. Angular ships several:

<article [ngClass]="{ thirsty: isThirsty(), sunny: likesSun() }">...</article>

<div [ngStyle]="{ 'width.%': waterLevel(), background: gaugeColour() }"></div>

<input [(ngModel)]="nickname" />
  • NgClass adds each class whose condition is true.
  • NgStyle sets several inline styles from an object.
  • NgModel (from FormsModule) links a form field to a value, as you saw with two-way binding.

Like any directive, each must be listed in the component's imports.

For classes and styles you often do not need a directive at all. The plain [class] and [style] bindings accept the same kinds of objects:

<article [class]="{ thirsty: isThirsty(), sunny: likesSun() }">...</article>
<div [style]="{ width: waterLevel() + '%' }"></div>

These are built in, need no imports and are the first choice in new code. For one class, [class.thirsty]="isThirsty()" is shorter still.

A single element can carry many attribute directives at once, alongside at most one structural directive. They do not compete for the element because none of them wraps it in a template.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.