Sub topic 6
Configuring a directive with inputs
This chapter shows how a template passes values into an attribute directive. It covers signal inputs, aliases (including one that matches the directive's selector), required inputs, and value transforms. It assumes you know TypeScript classes and decorators, standalone components with an imports array, and property and event binding in templates. It also assumes you have read the earlier chapters on @Directive, applying a directive, and host bindings, and that you use a recent Angular version with signal inputs.
Why a directive needs inputs
A directive that hard-codes yellow only works for one design. Inputs let the template author configure behavior per element. An input is a class property that Angular fills from the template, either from a static attribute or from a binding.
Since Angular 17.1 you declare inputs with the input() function from @angular/core. It returns a read-only signal, so you read the current value by calling it: this.color().
import { Directive, input } from '@angular/core';
@Directive({
selector: '[appHighlight]',
})
export class HighlightDirective {
color = input('yellow');
}Here color is an InputSignal<string>. The argument to input() is the default value, and it also sets the type. Angular uses the default until the template supplies a value.
The diagram below shows how a value travels from the template to the DOM.
Static values and bound values
The same input accepts two forms in a template.
- A static attribute,
color="red", always passes the string"red". - A property binding,
[color]="expr", passes the result of the expression, whatever its type, and updates it whenever the expression changes.
With a static attribute, the type is always string. If the input is typed as number or boolean, size="3" still delivers the string "3". A transform (covered below) solves this.
An input that shares the selector name
An attribute directive is applied by its selector, such as appHighlight. It is natural to let that same attribute carry the main value: appHighlight="lightblue". You do this with the alias option, which sets the name the template uses.
The directive below combines three inputs. One uses the selector name as its alias. The other two use prefixed aliases to avoid collisions with other attributes.
import { Directive, booleanAttribute, computed, input, signal } from '@angular/core';
@Directive({
selector: '[appHighlight]',
host: {
'[style.backgroundColor]': 'background()',
'(mouseenter)': 'active.set(true)',
'(mouseleave)': 'active.set(false)',
},
})
export class HighlightDirective {
readonly color = input('', { alias: 'appHighlight' });
readonly fallback = input('yellow', { alias: 'appHighlightFallback' });
readonly disabled = input(false, {
alias: 'appHighlightDisabled',
transform: booleanAttribute,
});
readonly active = signal(false);
readonly background = computed(() =>
this.active() && !this.disabled() ? this.color() || this.fallback() : null,
);
}Template usage:
<p appHighlight>Yellow on hover</p>
<p appHighlight="lightblue">Light blue on hover</p>
<p [appHighlight]="theme()">Color from a signal</p>
<p appHighlight appHighlightFallback="orange">Orange on hover</p>
<p appHighlight appHighlightDisabled>Never highlighted</p>
<p appHighlight [appHighlightDisabled]="readOnly()">Conditionally disabled</p>Three details explain why this works.
- A bare attribute such as
<p appHighlight>supplies the empty string""to the aliased input. That is why the computed value usesthis.color() || this.fallback(). The empty string is falsy, so the fallback applies. - The directive matches on the attribute name in its selector. The input with the same alias is a separate mechanism that happens to read the same attribute.
- The class property is still called
color. The alias only changes the public name. Inside the class you always usethis.color().
Returning null from the style binding removes the inline style. That makes the hover end cleanly without calling Renderer2.
Naming and the alias contract
The alias is part of the directive's public API. Renaming it breaks every template that uses it, while renaming the class property does not. Keep these rules in mind.
- Prefix aliases with the directive's prefix (
appHighlightFallback). Plain names likecolorordisabledcan collide with native attributes or with inputs of components on the same element. - Do not alias an input to the name of a native DOM property you do not mean to bind. Angular treats a binding as an input first, so
[title]would go to your directive and not to the element if you alias an input totitle. Other directives and components on that element receive the value as well. - If you do not need a different public name, skip
alias. Do not alias only to rename for style.
Required inputs
Use input.required<T>() when the directive cannot work without a value. It takes no default value, and Angular reports a compile-time error if a template omits it.
import { Directive, input } from '@angular/core';
@Directive({
selector: '[appTooltip]',
host: {
'[attr.title]': 'text()',
},
})
export class TooltipDirective {
readonly text = input.required<string>({ alias: 'appTooltip' });
}<button appTooltip="Save changes"> compiles. <button appTooltip> also compiles, because the bare attribute passes "". The compiler only checks that the input is present. It does not reject an empty string, so validate content yourself if an empty value is harmful.
Reading a required input before Angular has set it throws an error (NG0950). That can happen if you read it in the constructor or in a field initializer. Read it in a computed, an effect, a host binding, or from ngOnInit onward.
Transforming input values
Static attributes arrive as strings, so a transform converts the raw value to the type you want. Pass a pure function as transform.
Angular ships two ready-made transforms.
| Transform | Raw value | Result |
|---|---|---|
| `booleanAttribute` | `""` (bare attribute) | `true` |
| `booleanAttribute` | `"false"` | `false` |
| `booleanAttribute` | `undefined`, `null` | `false` |
| `numberAttribute` | `"3"` | `3` |
| `numberAttribute` | `"abc"` | `NaN` (or a fallback you pass) |
With a transform, the input's type has two parts: the type the template may pass in, and the type you read. For booleanAttribute the template may pass string | boolean | undefined | null, but the signal holds a boolean.
You can write your own transform. This one clamps a number into a range.
import { Directive, input, numberAttribute } from '@angular/core';
function clampPercent(value: unknown): number {
const n = numberAttribute(value, 0);
return Math.min(100, Math.max(0, n));
}
@Directive({
selector: '[appProgress]',
host: {
'[style.width.%]': 'percent()',
},
})
export class ProgressDirective {
readonly percent = input(0, { alias: 'appProgress', transform: clampPercent });
}<div appProgress="150"> sets the width to 100%, and <div [appProgress]="value()"> clamps every new value. Keep transforms pure and free of side effects, because Angular may call them at any time while it updates bindings, and the compiler needs to read the function's signature.
Reacting to input changes
Signal inputs are reactive, so you rarely need lifecycle hooks to follow them. Choose the tool by what you want to do.
| Goal | Use |
|---|---|
| Derive a value from inputs | `computed()` |
| Bind a derived value to the host | `host` metadata reading the signal |
| Run a side effect when an input changes | `effect()` |
| Run one-time setup that needs the first value | `ngOnInit` |
An effect is the right tool when you must call an imperative API, for example setting an attribute through Renderer2.
import { Directive, ElementRef, Renderer2, effect, inject, input } from '@angular/core';
@Directive({
selector: '[appLabel]',
})
export class LabelDirective {
private readonly el = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly renderer = inject(Renderer2);
readonly text = input('', { alias: 'appLabel' });
constructor() {
effect(() => {
this.renderer.setAttribute(this.el.nativeElement, 'aria-label', this.text());
});
}
}The effect reads this.text(), so Angular reruns it each time the input changes. Prefer a host binding ('[attr.aria-label]': 'text()') when the work is only a binding. Use an effect when it is not.
The decorator form
Older code declares inputs with the @Input() decorator. It still works, and you will meet it in existing projects.
import { Directive, Input } from '@angular/core';
@Directive({ selector: '[appLegacy]' })
export class LegacyDirective {
@Input('appLegacy') color = '';
}The differences that matter in practice:
- A decorator input is a plain property, so you read
this.colorand detect changes withngOnChangesor a setter. - A signal input is read-only. Assigning
this.color = 'red'is a compile error, which prevents the directive from fighting its template. - Signal inputs support
input.requiredwith compile-time checks, and transforms are built in.
Do not mix the two styles in one directive without a reason.
Common errors
Can't bind to 'x' since it isn't a known property of 'p'. The element has no directive that declares an input with that name. Either the alias is misspelled, or the directive is missing from the component'simportsarray.- A boolean input is always true. Writing
disabled="false"on a plainbooleaninput passes the string"false", which is truthy. UsebooleanAttribute. - The input holds its default value in the constructor. Angular sets inputs after construction. Move the logic into a
computed, aneffect, orngOnInit. NG0950when reading a required input. The read happened before the first binding. See the previous point.- The value looks stale after mutating an object. Angular compares input values by reference. If you pass the same object and change its fields, the input does not signal a change. Pass a new object or use a signal.
- A bare selector attribute gives
"", nottrue. For a flag, addbooleanAttribute. For a value with a default, treat""as unset as shown above.
Testing inputs
Test a directive's inputs through a host component, so the template does the binding as it would in an app. Bind the input to a signal in the host and change it.
import { Component, signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { HighlightDirective } from './highlight.directive';
@Component({
imports: [HighlightDirective],
template: `<p [appHighlight]="color()">Text</p>`,
})
class TestHostComponent {
color = signal('lightblue');
}
describe('HighlightDirective inputs', () => {
it('follows the bound color', () => {
const fixture = TestBed.createComponent(TestHostComponent);
const p = fixture.nativeElement.querySelector('p') as HTMLElement;
p.dispatchEvent(new Event('mouseenter'));
fixture.detectChanges();
expect(p.style.backgroundColor).toBe('lightblue');
fixture.componentInstance.color.set('pink');
fixture.detectChanges();
expect(p.style.backgroundColor).toBe('pink');
});
});Summary
- Declare inputs with
input(), and read them by calling the signal. - Use
aliasto expose a clean public name, including the selector name for the main value. - Use
input.requiredwhen a value is mandatory, andtransform(booleanAttribute,numberAttribute, or your own pure function) to convert static strings. - Derive values with
computed, bind them with host metadata, and useeffectonly for imperative work.
Exercise
A directive declares readonly enabled = input(true); and is used as <p appFeature enabled="false">. The aliased attribute is correctly matched, yet the feature stays on. Why does this happen, and how do you fix the input declaration so that enabled="false" turns it off and a bare enabled turns it on?
Show answer
A static attribute always passes a string, so the input receives the string "false". Any non-empty string is truthy, so the feature stays on. Add the built-in transform: readonly enabled = input(true, { transform: booleanAttribute });. Then "false" becomes false, and the bare attribute enabled (value "") becomes true.
Exercise
You write <p appHighlight> for a directive with color = input('', { alias: 'appHighlight' }) and a host binding '[style.backgroundColor]': 'color()'. The paragraph gets no background color. What value does the input hold, and what is a simple fix?
Show answer
The bare attribute passes the empty string, so color() is "" and the style binding sets nothing useful. Fall back to a default, for example color() || 'yellow', or compute the value in a computed() that substitutes a fallback when the input is empty.