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" />NgClassadds each class whose condition is true.NgStylesets several inline styles from an object.NgModel(fromFormsModule) 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.
The shortcut
Ask: "After this runs, is the element still on the page?" If yes, and it simply looks or acts differently, you want an attribute directive or a class/style binding. If it might vanish or be repeated, you want a structural directive or a control-flow block.
Still on the page?
Yes, the card stays; it only changes colour. So this is attribute territory.
The trap is reaching for @if to show a card in two different colours by duplicating the whole card. Keep one card and change its classes.
Drills
Answer fast — trust the rule.
Which is an attribute directive?
What does [ngClass]="{ thirsty: true, sunny: false }" produce?
What must you do before using [ngStyle] in a standalone component?
A card should look faded while dragging() is true. What is the simplest fit?
Remember
- Attribute directives change an element; structural directives add or remove elements.
NgClass,NgStyleandNgModelmust be imported; plain[class]and[style]are built in and preferred.- Trap: duplicating markup with
@ifwhen a class change would do.
