Sub topic 6
Configuring a Directive with Inputs
This chapter assumes you know TypeScript classes and decorators, Angular standalone components with the imports array, and basic property binding in templates. It builds on the HighlightDirective from earlier chapters and shows how to let the template configure it.
Why directives need inputs
So far the directive always uses yellow. A reusable directive should let each element choose its own value. An input is a class property that the template can set, the same way a component receives data from its parent.
Angular's signal-based input() function creates an input. It returns a read-only signal, so you read the current value by calling it, as in color().
An input that shares the selector name
A common pattern is to give the input the same name as the attribute selector. The user then writes one attribute that both applies the directive and passes the value.
import { Directive, input, signal } from '@angular/core';
@Directive({
selector: '[appHighlight]',
host: {
'[style.backgroundColor]': 'active() ? (color() || "yellow") : null',
'(mouseenter)': 'active.set(true)',
'(mouseleave)': 'active.set(false)',
},
})
export class HighlightDirective {
color = input('', { alias: 'appHighlight' });
active = signal(false);
}Three parts matter here:
input('', ...)declares an input with an empty string as its default value. Angular infers the typestring.{ alias: 'appHighlight' }makes the template name differ from the property name. The class property iscolor, but the template usesappHighlight.- The
hostmetadata readscolor()inside a binding. Angular tracks the signal, so the style updates whenever the input changes.
The expression color() || "yellow" falls back to yellow when the input is an empty string. That happens when the attribute is written without a value.
Using the input in a template
<p appHighlight>Default yellow on hover</p>
<p appHighlight="lightblue">Light blue on hover</p>In the first line the attribute has no value, so color() is '' and the fallback applies. In the second line the string lightblue is passed as a static value.
You can also bind to it with square brackets. The bound expression is evaluated by Angular and passed in.
<p [appHighlight]="chosenColor">Color comes from the component</p>How the data flows
The style depends on two signals, color() and active(). A change to either one re-evaluates the binding.
Input options worth knowing
The input() function takes an options object. Two options come up often.
| Option | Purpose | Example |
|---|---|---|
| `alias` | Sets the name used in the template | `input('', { alias: 'appHighlight' })` |
| `transform` | Converts the raw template value before it is stored | `input(false, { transform: booleanAttribute })` |
Use input.required<string>() when the directive cannot work without a value. Angular then reports an error at compile time if the template omits it. A required input has no default, so it cannot also fall back to yellow.
Common errors
- Forgetting to call the signal. Writing
colorinstead ofcolor()in a host binding gives you the signal object, not the string. - Using the property name in the template. With an alias,
[color]="x"fails. Use the alias,[appHighlight]="x". - Reading inputs in the constructor. Input values are not set yet when the constructor runs. Read them in bindings, in a
computed, or in aneffect. - Passing a non-string to a static attribute.
appHighlight="5"always passes the string'5'. Use property binding,[appHighlight]="5", for other types. - Missing import. The directive only receives inputs on elements in templates where the component lists it in
imports.
A derived value with computed
If you need to process the input, wrap it in computed rather than repeating logic in the host string.
import { Directive, computed, input, signal } from '@angular/core';
@Directive({
selector: '[appHighlight]',
host: {
'[style.backgroundColor]': 'background()',
'(mouseenter)': 'active.set(true)',
'(mouseleave)': 'active.set(false)',
},
})
export class HighlightDirective {
color = input('', { alias: 'appHighlight' });
active = signal(false);
background = computed(() => (this.active() ? this.color() || 'yellow' : null));
}The behavior is identical. The host string is shorter and the logic can be read and tested as ordinary code.
Exercise
A directive declares size = input(12, { alias: 'appSize' }). Which template line sets it to 20 using a number, and why does appSize="20" not do the same?
Show answer
Use [appSize]="20". Property binding evaluates the expression and passes the number 20. A plain attribute appSize="20" is a static string, so the input receives '20'. The input's inferred type is number, so the static form would not type-check. You could add transform: numberAttribute to accept the string form.
Exercise
Add a second input named hoverColor (no alias) to the directive so that <p appHighlight="red" hoverColor="blue"> is not needed to use the first one. What default should it have, and how do you read it in a host binding?
Show answer
Declare hoverColor = input('yellow'); with a default of 'yellow'. Read it as hoverColor() in the host expression or in a computed. Because it has a default, templates that omit it still work.