Sub topic 14
Pitfalls and conventions
This chapter collects the mistakes that most often appear when you work with input(), output(), and model(), and the naming habits that keep components easy to use. It assumes you can write standalone components, bind with [prop] and (event), and read signals by calling them. It also assumes you have seen computed() and effect().
Inputs are read-only inside the child
An input() returns an InputSignal. The parent owns its value, so the child can read it but cannot call set() or update() on it. TypeScript reports this as a compile error.
import { Component, input } from '@angular/core';
@Component({
selector: 'app-badge',
template: `<span>{{ label() }}</span>`,
})
export class Badge {
label = input('');
reset() {
// Error: Property 'set' does not exist on type 'InputSignal<string>'.
// this.label.set('');
}
}If the child needs a local, editable copy that starts from the input, use linkedSignal(). It resets to the input's value whenever the input changes, and you can still write to it.
import { Component, input, linkedSignal } from '@angular/core';
@Component({
selector: 'app-name-editor',
template: `<input [value]="draft()" (input)="onInput($event)" />`,
})
export class NameEditor {
name = input.required<string>();
draft = linkedSignal(() => this.name());
onInput(event: Event) {
this.draft.set((event.target as HTMLInputElement).value);
}
}If the child should change the parent's value, use model() and a two-way binding instead. Do not copy an input into a writable signal with effect(). That pattern runs one change late and is harder to follow than computed() or linkedSignal().
Reading an input too early
Input values arrive after Angular creates the component instance. A field initializer and the constructor both run before that, so an input read there has no value yet. For a required input, the read throws an error (NG0950). For an optional input you silently get the default value.
import { Component, OnInit, input } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `<p>Hello, {{ name() }}</p>`,
})
export class Greeting implements OnInit {
name = input.required<string>();
constructor() {
// Throws NG0950: the value has not been set yet.
// console.log(this.name());
}
ngOnInit() {
console.log(this.name()); // Safe: inputs are set before ngOnInit.
}
}The safe places to read an input are the template, computed(), effect(), and lifecycle hooks from ngOnInit onward. A computed() can be declared in a field initializer because it only runs when something reads it.
Declaring inputs and outputs in the wrong place
input(), input.required(), output(), and model() only work as class field initializers, because Angular needs an injection context and a compile-time transform to find them. You cannot call them inside a method, a constructor body, or a conditional. You also cannot assign one of these functions to a field from another class.
- Write
size = input(16);as a class field. - Do not write
this.size = input(16);insidengOnInit. - Do not wrap the call in a helper function that returns the input. The compiler cannot see it.
Forgetting the parentheses
An input is a signal, so you read it by calling it. In the template, {{ name }} shows the signal function itself, not its value. In TypeScript, this.name.length fails to compile for a string input. The call is this.name().length. Always call the signal in computed() too, because that call is what registers the dependency.
Static attributes are strings
When a parent writes size="20" without brackets, Angular passes the string "20". The binding [size]="20" passes a number. Mixing these up is a common source of bugs, especially with booleans, where a bare disabled attribute is an empty string.
| Parent template | Value the child receives (no transform) |
|---|---|
| `size="20"` | `"20"` (string) |
| `[size]="20"` | `20` (number) |
| `disabled` | `""` (empty string, which is falsy) |
| `[disabled]="true"` | `true` |
For inputs that parents often write as plain attributes, declare a transform. numberAttribute and booleanAttribute handle these cases. booleanAttribute treats an empty string as true and the string "false" as false.
import { Component, booleanAttribute, input, numberAttribute } from '@angular/core';
@Component({
selector: 'app-chip',
template: `<span [style.font-size.px]="size()">{{ disabled() ? 'off' : 'on' }}</span>`,
})
export class Chip {
size = input(16, { transform: numberAttribute });
disabled = input(false, { transform: booleanAttribute });
}Keep a transform simple and free of side effects. It runs every time the parent supplies a new value, and it must not depend on other inputs or signals.
Mutating objects that arrive as inputs
Making the input read-only does not make its contents read-only. If the parent passes an object or an array, the child can still change it with user().name = 'x' or items().push(item). This changes the parent's data without the parent noticing, and it can break OnPush change detection and any computed() that depends on that object.
Treat object inputs as immutable. To change one, emit an output that carries the new value, and let the parent replace its own state.
import { Component, input, output } from '@angular/core';
interface Todo {
id: number;
done: boolean;
}
@Component({
selector: 'app-todo-row',
template: `<input type="checkbox" [checked]="todo().done" (change)="toggle()" />`,
})
export class TodoRow {
todo = input.required<Todo>();
updated = output<Todo>();
toggle() {
this.updated.emit({ ...this.todo(), done: !this.todo().done });
}
}Output pitfalls
Outputs have a few traps that differ from inputs.
- They do not bubble. Unlike native DOM events, an output only reaches the parent that binds it. A grandparent cannot hear it unless the parent re-emits it.
- Emitting too early reaches nobody. Calling
emit()in the constructor or a field initializer happens before the parent subscribes, so the event is lost. Emit from event handlers, effects, or lifecycle hooks afterngOnInit. - Names that match native events cause confusion. An output called
clickorchangefires alongside the element's real DOM event. A listener such as(click)="save()"on the component's tag can run twice: once for the output and once for the DOM event that bubbles up from the child's own elements. Choose a different name. - Emit data, not the framework event. Emit a typed value such as a number or an object. Passing a raw DOM
Eventties the parent to the child's markup.
Naming and style conventions
Following the same conventions as the rest of the Angular ecosystem makes your components predictable.
| Item | Convention | Example |
|---|---|---|
| Input | A noun for the data it holds | `user`, `step`, `items` |
| Output | A verb or event name, not prefixed with `on` | `saved`, `changed`, `closed` |
| Output handler in the parent | Prefixed with `on` | `(saved)="onSaved($event)"` |
| Model | A noun, with the generated output named `<name>Change` | `checked` and `checkedChange` |
| Alias | Avoid unless you are keeping a public name stable | `input('', { alias: 'label' })` |
A few more habits help:
- Mark input, output, and model fields
readonlyso nobody reassigns the field itself. - Do not name an input after a native HTML attribute such as
title,id, orhidden. The browser attribute and your input then compete on the same element. - Prefer
computed()for values derived from inputs, and keepeffect()for side effects such as logging or calling a non-Angular library. - Choose
input.required()when the component makes no sense without a value. A default that hides a missing value is a worse bug than a compile error. - Set
changeDetection: ChangeDetectionStrategy.OnPushon components that use signal inputs. They update correctly and avoid extra checks.
A quick checklist
Before you finish a component, check these points.
- Every input is read by calling it, and none is read in a constructor or field initializer except inside
computed()oreffect(). - No code tries to
set()an input, and object inputs are never mutated. - Attribute-style inputs have a
numberAttributeorbooleanAttributetransform where needed. - Output names are events in the past tense or plain verbs, with no
onprefix and no clash with native DOM events. - Two-way bindings use
model(), and the parent binds a writable signal or plain property.
Exercise
A component declares count = input.required<number>(); and its constructor contains console.log(this.count());. The parent binds [count]="5". Why does the app still throw, and where should the read move?
Show answer
The constructor runs before Angular sets any input values, so reading a required input there throws NG0950 even though the parent supplies a value. Move the read to ngOnInit, to a computed(), to an effect(), or to the template, where the value is already set.
Exercise
A child has items = input.required<string[]>(); and calls this.items().push('new') when a button is clicked. Name two problems with this and describe a better design.
Show answer
First, it mutates the parent's array without the parent knowing, which can break OnPush change detection and stale any computed() that depends on it. Second, it hides the data flow, because the parent's state changes from inside the child. A better design declares added = output<string>(); and emits the new item. The parent then replaces its own array with a new one, for example this.items.update(list => [...list, item]).