Sub topic 2
Computing values from inputs
Assume you know standalone components, property binding, event binding, and that signals are read by calling them.
Computing values from inputs
An input is a read-only signal whose value comes from a parent. Use computed() when a child needs a value derived from one or more inputs. Angular tracks the dependency and recalculates the result when an input changes.
import { Component, computed, input, output } from '@angular/core';
@Component({
selector: 'app-user-card',
standalone: true,
template: `
<h2>{{ name() }}</h2>
<p>Initials: {{ initials() }}</p>
<button (click)="select()">Select</button>
`,
})
export class UserCard {
name = input.required<string>();
initials = computed(() =>
this.name()
.split(' ')
.map((part) => part[0])
.join('')
);
selected = output<string>();
select() {
this.selected.emit(this.name());
}
}Do not assign to name. The parent owns that state. Also, read name() inside computed(), rather than copying its value into a normal field.
Declaring and handling outputs
An output is a typed event channel from a child to its parent. Declare it with output<T>(), then call emit() with a value of type T.
The parent listens with event binding. Angular places the emitted value in $event.
<app-user-card
[name]="user.name"
(selected)="onUserSelected($event)"
/>The handler receives a string because selected is an output<string>().
Aliasing an input
Use alias when the public template name should differ from the TypeScript property name. This can preserve an existing API while using a clearer internal name.
export class Badge {
label = input('', { alias: 'text' });
}A parent uses the alias:
<app-badge text="Online" />Inside the component, read label().
Exercise
Why should a derived value use computed(() => this.name()) instead of assigning this.name() once to a field?
Show answer
computed() tracks the input and updates the derived value whenever the parent supplies a new name.