Sub topic 9
Transforming input values
This chapter assumes you know Angular standalone components, property and attribute binding in templates, and how to declare inputs with input() and input.required(). You should also know that a signal is read by calling it.
Why inputs need transforms
A parent can pass values to a child in two ways: as a binding such as [size]="20", or as a plain HTML attribute such as size="20". A plain attribute always arrives as a string. A bare attribute such as disabled arrives as an empty string. If the child declares size = input(16), Angular infers the type number, and the template type checker rejects size="20" because a string is not a number.
An input transform solves this. It is a function you attach to the input. Angular runs it every time the parent supplies a value, and the input stores the result. The child always reads the cleaned-up value, whatever form the parent used.
The shape of a transform
Pass the function in the options object as transform:
import { Component, booleanAttribute, input, numberAttribute } from '@angular/core';
@Component({
selector: 'app-icon-button',
template: `
<button [disabled]="disabled()" [style.font-size.px]="size()">{{ text() }}</button>
`,
})
export class IconButton {
size = input(16, { transform: numberAttribute });
disabled = input(false, { transform: booleanAttribute });
text = input('', { alias: 'label' });
}Two types are involved, and they are the main idea of this chapter:
- The stored type is what the child reads. For
sizeit isnumber. - The accepted type is what the parent may bind. It is the type of the transform function's parameter. For
numberAttributeit isunknown.
The input's type reflects this. size is an InputSignalWithTransform<number, unknown>. Calling size() returns a number, and the parent may bind anything.
<app-icon-button size="20" disabled label="Save" />
<app-icon-button [size]="24" [disabled]="false" label="Cancel" />In the first line, size="20" becomes the number 20 and the bare disabled becomes true.
The built-in transforms
Angular ships two transforms for the most common cases.
| Function | Parent passes | Child reads |
|---|---|---|
| `booleanAttribute` | `''` (bare attribute), `'true'`, any other non-null value except `'false'` | `true` |
| `booleanAttribute` | `'false'`, `false`, `null`, `undefined` | `false` |
| `numberAttribute` | `'20'`, `20`, `'3.5'` | `20`, `20`, `3.5` |
| `numberAttribute` | `'abc'`, `undefined` | `NaN` |
numberAttribute accepts an optional second argument, a fallback used instead of NaN. To use it as a transform, wrap it in your own named function:
import { Component, input, numberAttribute } from '@angular/core';
function sizeAttribute(value: unknown): number {
return numberAttribute(value, 16);
}
@Component({
selector: 'app-badge',
template: `<span [style.font-size.px]="size()">badge</span>`,
})
export class Badge {
size = input(16, { transform: sizeAttribute });
}Now size="large" yields 16 instead of NaN.
Writing your own transform
A transform is an ordinary function that takes the parent's value and returns the stored value. Use it to normalize input at the boundary, so the rest of the component never handles messy cases.
import { Component, input } from '@angular/core';
function clampPercent(value: number | string | null | undefined): number {
const n = Number(value);
if (Number.isNaN(n)) {
return 0;
}
return Math.min(100, Math.max(0, n));
}
@Component({
selector: 'app-progress-bar',
template: `
<div class="track">
<div class="fill" [style.width.%]="value()"></div>
</div>
<span>{{ value() }}%</span>
`,
})
export class ProgressBar {
value = input(0, { transform: clampPercent });
}<app-progress-bar [value]="150" />
<app-progress-bar value="42" />
<app-progress-bar [value]="null" />These render 100%, 42%, and 0%. The parent may bind a number, a string, null, or undefined, because those are the types clampPercent accepts. A boolean would be a compile error under strict templates.
The same pattern works for strings:
import { Component, input } from '@angular/core';
function trimString(value: string | undefined): string {
return value?.trim() ?? '';
}
@Component({
selector: 'app-field-label',
template: `<label>{{ text() }}</label>`,
})
export class FieldLabel {
text = input('', { transform: trimString });
}Transforms with required inputs and aliases
Transforms combine with the other options. For a required input, there is no initial value to infer types from, so you give both type arguments: the stored type first, then the accepted type.
import { Component, computed, input, numberAttribute } from '@angular/core';
@Component({
selector: 'app-rating',
template: `
@for (star of stars(); track star) {
<span>★</span>
}
`,
})
export class Rating {
max = input.required<number, unknown>({ transform: numberAttribute });
stars = computed(() => Array.from({ length: this.max() }, (_, i) => i + 1));
}<app-rating max="5" /> is valid, and stars() has five entries. An input can also use alias and transform together, for example input(0, { alias: 'count', transform: numberAttribute }).
Rules the transform must follow
Angular's compiler reads the transform's parameter type to type-check parent templates, so a transform has constraints.
- Keep it pure. It should compute its result from its argument only. No side effects, no HTTP calls, no writing to other signals.
- Keep it synchronous. It returns a value, not a promise or an observable.
- Reference a function whose parameter type is declared. A function with a clear signature gives the checker the accepted type.
- Do not depend on other inputs or on component state. A transform sees one value in isolation.
When the transform runs
The transform runs when Angular writes a value into the input, once per new value from the parent binding. It does not run on every read. Reading value() a hundred times returns the same stored result. If the parent binding does not change between change detection passes, the transform does not run again.
Two consequences follow:
- If the parent never binds the input, the transform never runs. The initial value you passed to
input()is used as is. It is already of the stored type, so it is not transformed. - If the parent passes the same object reference after mutating it, Angular sees no change and does not call the transform again.
Transform or computed?
Both turn one value into another, but they serve different purposes. A transform changes what a single input stores, using only the value the parent sent. A computed() derives new state from one or more signals, including other inputs.
| Need | Use |
|---|---|
| Convert `"20"` to `20` at the boundary | transform |
| Clamp or trim the value the child stores | transform |
| Build `fullName` from `first()` and `last()` | `computed()` |
| Use the value together with other state | `computed()` |
You can use both on one input. The transform normalizes the raw value, and a computed() builds display data from the normalized value.
Common errors
- Assuming the transform changes what the parent sees. The parent sees the accepted type, the parameter type of the function. The child sees the return type.
- Passing
'false'to a plaininput(false). WithoutbooleanAttribute, the string'false'is a type error. With it, the value correctly becomesfalse. - Forgetting that
numberAttributeyieldsNaNfor bad input.NaNis falsy but not equal to anything, so checks likesize() === 0miss it. Supply a fallback. - Doing work in the transform that belongs in
computed(), such as combining two inputs. The transform cannot read the other input. - Using a transform on
model(). Themodel()function does not support thetransformoption, so coerce the value in the child, or use a separateinput(). - Writing a transform that throws. The error surfaces during change detection of the parent. Return a safe fallback instead.
Exercises
Exercise
A child declares count = input(0, { transform: numberAttribute }). The parent writes <app-child count="12" />. What type does the parent supply, what type does count() return, and does the transform run when the parent omits the count attribute entirely?
Show answer
The parent supplies the string "12" (accepted type unknown). count() returns the number 12. If the attribute is omitted, the transform does not run, and count() returns the initial value 0.
Exercise
Write an input named tags that accepts either a comma-separated string such as "a, b" or an array of strings, and always stores a string[] of trimmed, non-empty values. Give the transform function and the input declaration.
Show answer
function toTags(value: string | string[] | null | undefined): string[] { const parts = Array.isArray(value) ? value : (value ?? '').split(','); return parts.map((p) => p.trim()).filter((p) => p.length > 0); } tags = input<string[], string | string[] | null | undefined>([], { transform: toTags });