Sub topic 3
Transforming Input Values
Assume you know Angular standalone components, property and event binding, TypeScript generics, and basic signals. This chapter focuses on the less common input and output patterns.
Transforming input values
An input transform converts a value before the component reads it. Angular provides numberAttribute and booleanAttribute for common HTML attribute values. An alias changes the public binding name.
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' });
}The parent can write <app-icon-button size="20" disabled label="Save" />. Keep transforms pure. They should convert input data, not perform side effects.
Two-way binding with `model()`
Use model() when a child both reads a value and intentionally changes it. Angular creates a matching change output automatically.
import { Component, model } from '@angular/core';
@Component({
selector: 'app-toggle',
template: `<button (click)="toggle()">{{ checked() ? 'On' : 'Off' }}</button>`,
})
export class Toggle {
checked = model(false);
toggle() {
this.checked.update(value => !value);
}
}The parent uses <app-toggle [(checked)]="isOn" />. Prefer ordinary inputs and outputs when the child only reports an event.
When input values are available
Angular assigns bound inputs during component initialization, before ngOnInit. A field initializer, however, runs before the parent value arrives. Do not read a required input in the constructor. A computed() value is safer because it reads the current input when evaluated.
Outputs and RxJS
Declare typed events with output() and call emit(). A parent receives the value through $event. outputFromObservable() exposes an RxJS observable as an output. Conversely, outputToObservable() converts an output reference into an observable for RxJS operators.
Migrating from `@Input` and `@Output`
Replace @Input() name = '' with name = input(''), and read it as name(). Replace @Output() changed = new EventEmitter<number>() with changed = output<number>(), then use changed.emit(value). Update templates and tests that directly read or assign these fields.
Pitfalls and conventions
- Do not assign to an
input()signal. Inputs are read-only in the child. - Give required inputs to every component instance.
- Use event names that describe something that happened, such as
saved. - Use
model()only when two-way ownership is intentional. - Avoid side effects in transforms and
computed()functions.
Exercise
Which API fits a child toggle that reads and changes a parent's checked value?
Show answer
model(false), used by the parent with [(checked)].