Sub topic 6
Signal Inputs with input()
Component inputs are the main way a parent passes data to a child. Angular's input() function declares an input as a read-only signal. The value can then flow into computed() and effect() like any other signal, and you don't need lifecycle hooks to see when it changes.
This chapter assumes you know how to build Angular components with templates and property binding, and that you understand writable signals, computed(), and effect() from the earlier chapters. Two-way binding with model() and events with output() have their own chapters, so they come up here only for contrast.
From @Input to input()
The decorator-based API stores an input in a plain class property:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-greeting-legacy',
template: `<p>Hello, {{ name }}</p>`,
})
export class GreetingLegacyComponent {
@Input() name = '';
}Angular writes a new value to name whenever the parent binding changes. Nothing notifies your code, so any value derived from name has to be recomputed in ngOnChanges or in a setter. The signal version looks like this:
import { Component, computed, input } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `<p>{{ greeting() }}</p>`,
})
export class GreetingComponent {
name = input('');
greeting = computed(() => `Hello, ${this.name()}`);
}name is now an InputSignal<string>. You read it by calling it, and any computed() or effect() that reads it picks up changes automatically. The derivation is a single line, and you no longer need to compare previous and current values yourself.
| Concern | `@Input()` property | `input()` signal |
|---|---|---|
| Reading the value | `this.name` | `this.name()` |
| Reacting to changes | `ngOnChanges` or a setter | `computed()` / `effect()` |
| Required inputs | `@Input({ required: true })`, type still needs `!` | `input.required<T>()`, type is `T` |
| Writable from inside the child | Yes (often a bug) | No, read-only |
| Works with OnPush and zoneless | Needs a binding change or `markForCheck` | Signal reads notify the view directly |
Declaring inputs
Optional inputs with a default
input(defaultValue) creates an optional input. TypeScript infers the type from the default:
size = input(48); // InputSignal<number>
variant = input<'round' | 'square'>('round');If you give no default, the type includes undefined:
tooltip = input<string>(); // InputSignal<string | undefined>The type is accurate. If the parent doesn't bind tooltip, the value really is undefined, and the compiler makes you handle that case.
Required inputs
input.required<T>() declares an input that the parent must bind. The compiler reports an error in any template that uses the component without it. The signal's type is T with no undefined, so you don't need the non-null assertion (!) that decorator inputs required.
userId = input.required<number>();Aliases
The alias option sets the public binding name while keeping a different property name inside the class:
userId = input.required<number>({ alias: 'id' });The parent writes [id]="42", and the class reads this.userId(). Use aliases sparingly. They mostly help when you migrate an existing public API without breaking the components that consume it.
Transforms
A transform converts the raw bound value before the signal stores it. Angular provides two transforms that cover the most common cases:
import { booleanAttribute, input, numberAttribute } from '@angular/core';
disabled = input(false, { transform: booleanAttribute });
columns = input(3, { transform: numberAttribute });With booleanAttribute, a bare attribute like <app-card disabled /> sets the input to true. Without the transform, the attribute would pass the empty string ''. numberAttribute turns columns="4" into the number 4.
A transform must be a pure function. It runs every time the bound value changes, and it should not read other signals or cause side effects. If an output depends on more than one input, derive it with computed() instead.
A complete example
The component below combines every option covered so far:
import {
Component,
booleanAttribute,
computed,
effect,
input,
numberAttribute,
} from '@angular/core';
export interface User {
id: number;
name: string;
avatarUrl: string;
}
@Component({
selector: 'app-user-card',
template: `
<article [class.compact]="compact()" [style.width.px]="size() * 4">
<img [src]="user().avatarUrl" [width]="size()" [height]="size()" alt="" />
<h3>{{ displayName() }}</h3>
@if (badge(); as text) {
<span class="badge">{{ text }}</span>
}
</article>
`,
})
export class UserCardComponent {
user = input.required<User>();
size = input(48, { transform: numberAttribute });
compact = input(false, { transform: booleanAttribute });
badge = input<string>();
prefix = input('', { alias: 'namePrefix' });
displayName = computed(() => {
const p = this.prefix();
return p ? `${p} ${this.user().name}` : this.user().name;
});
constructor() {
effect(() => {
console.log(`Rendering card for user ${this.user().id}`);
});
}
}A parent can use it like this:
<app-user-card [user]="selectedUser()" size="64" compact namePrefix="Dr." />
<app-user-card [user]="otherUser" badge="Admin" />Each attribute shows a different mechanism. size="64" is a static string that numberAttribute converts to a number. compact has no value, and booleanAttribute turns it into true. namePrefix is the alias for prefix. In the second card, badge is bound and prefix falls back to its default of ''.
Timing: when input values exist
Angular sets input values during change detection of the parent, before the child's ngOnInit runs. That ordering produces the most common mistake with required inputs.
Reading a required input too early
A required input has no value when the constructor runs. Reading it there throws runtime error NG0950, which says the input is required but no value is available yet:
constructor() {
console.log(this.user().name); // throws NG0950
}Code that works fine in the constructor:
- Creating
computed()signals that read inputs. A computed signal is lazy, so it doesn't read anything until someone asks for its value. - Creating
effect()s that read inputs. Effects first run during change detection, after the inputs have been set. - Reading inputs in
ngOnInitor later lifecycle hooks.
Optional inputs never throw. Before binding they return their default value, which can still mislead you: in the constructor, size() returns 48 even when the parent will soon bind 64.
Declaration rules
input() and input.required() must be called in a class field initializer. The Angular compiler finds inputs by looking for those calls. A call inside the constructor, inside a method, or assigned to a variable outside the class is not registered as an input, and the compiler reports an error.
Read-only by design
An InputSignal has no set() or update() method. Only the parent decides the value of an input. Decorator inputs allowed code such as this.name = 'x' inside the child. The local write and the parent's next binding update then overwrote each other, and the child and parent disagreed about the value.
You can handle a child that needs its own editable copy in two ways:
- If the parent should see the edits, use
model(), which the next chapter covers. - If the state is local and should reset when the input changes, use
linkedSignal(), which a later chapter covers.
Equality and object inputs
The template binding decides whether an input has changed by comparing the old and new values by identity. If the parent mutates an object in place, as in user.name = 'Grace', the reference stays the same. The child's input signal does not change, and displayName keeps its stale value. Give the child a new object instead, for example selectedUser.set({ ...u, name: 'Grace' }). This is the same immutable-update rule that writable signals follow.
Testing signal inputs
A signal input cannot be assigned directly in a test, because component.user is a function. Set inputs through the component reference instead:
import { TestBed } from '@angular/core/testing';
import { UserCardComponent } from './user-card.component';
it('prefixes the display name', () => {
const fixture = TestBed.createComponent(UserCardComponent);
fixture.componentRef.setInput('user', { id: 1, name: 'Ada', avatarUrl: '/a.png' });
fixture.componentRef.setInput('namePrefix', 'Dr.');
fixture.detectChanges();
expect(fixture.componentInstance.displayName()).toBe('Dr. Ada');
});setInput takes the public name, which means the alias when one is set. It also runs any transform, just as a template binding would.
Common errors at a glance
| Symptom | Cause | Fix |
|---|---|---|
| NG0950 at startup | Required input read in the constructor | Read it in `computed()`, `effect()`, or `ngOnInit` |
| Template shows `[object Object]` or a function body | Wrote `{{ user }}` instead of `{{ user() }}` | Call the signal |
| `disabled` attribute has no effect | Bare attribute passes `''` | Add `transform: booleanAttribute` |
| Child doesn't update after parent edits an object | In-place mutation keeps the same reference | Pass a new object |
| "Property 'set' does not exist" | Tried to write to an input | Use `model()` or `linkedSignal()` |
| Test sets `component.user = ...` and nothing happens | Replaced the signal with a value | Use `componentRef.setInput()` |
Exercise
A component declares pageSize = input.required<number>() and, in its constructor, runs this.items = new Array(this.pageSize()). It crashes on load. Explain why, and rewrite the code so items stays correct when the parent changes pageSize.
Show answer
A required input has no value until Angular sets it during the parent's change detection, which happens after the constructor. Reading it in the constructor throws NG0950. Declare a derived signal as a field instead: items = computed(() => new Array(this.pageSize())). A computed signal is lazy, so it doesn't read pageSize until the template asks for it, and it recomputes whenever the input changes.
Exercise
You want <app-panel collapsible /> and <app-panel [collapsible]="isMobile()" /> to both work, with collapsible defaulting to false when it isn't bound. Write the input declaration and explain what goes wrong without the transform.
Show answer
Declare collapsible = input(false, { transform: booleanAttribute }) and import booleanAttribute from @angular/core. Without the transform, the bare attribute passes the empty string ''. TypeScript rejects that for a boolean input, and at runtime '' is falsy, so the panel would act as if it were not collapsible. booleanAttribute maps '' and 'true' to true and passes real booleans through unchanged.