Sub topic 8
Aliasing inputs
This chapter assumes you can declare inputs with input() and input.required(), read them by calling them, and bind to them from a parent template. It covers the alias option: what it changes, when to use it, and where it causes trouble.
Two names for one input
A signal input has two names:
- The class field name is the property you write in TypeScript. Code inside the component uses it, for example
this.text(). - The public name is the name a parent uses in its template, for example
[label]="..."orlabel="...".
By default the two are identical. The alias option makes them different. The option goes in the options object, which is the last argument of input().
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' });
}Inside IconButton, the template and the class both use text(). A parent that uses the component writes label:
import { Component } from '@angular/core';
import { IconButton } from './icon-button';
@Component({
selector: 'app-toolbar',
imports: [IconButton],
template: `
<app-icon-button label="Save" size="20" />
<app-icon-button [label]="'Delete'" disabled />
`,
})
export class Toolbar {}The parent never sees text. Binding [text]="'Save'" fails at compile time, because the component has no input with that public name. Angular reports an error like "Can't bind to 'text' since it isn't a known property of 'app-icon-button'".
Where the alias goes
The alias is always part of the options object. The position of that object depends on the function.
| Declaration | Alias syntax | Parent uses |
|---|---|---|
| Optional input | `input('', { alias: 'label' })` | `[label]` or `label` |
| Optional input without a default | `input<string>(undefined, { alias: 'label' })` | `[label]` or `label` |
| Required input | `input.required<string>({ alias: 'label' })` | `[label]` or `label` |
| Output | `output<void>({ alias: 'dismissed' })` | `(dismissed)` |
| Model | `model(false, { alias: 'on' })` | `[on]`, `(onChange)`, `[(on)]` |
Two details in this table matter.
- For
input.required(), the options object is the only argument, because a required input has no default value. The type argument stays in angle brackets. - A
model()alias renames both halves of the pair. The input takes the alias, and the output becomes the alias plusChange. This keeps the[(on)]shorthand working.
You can combine alias with transform in the same options object:
import { Component, input, numberAttribute } from '@angular/core';
@Component({
selector: 'app-rating',
template: `<span>{{ value() }} / 5</span>`,
})
export class Rating {
value = input.required<number, unknown>({
alias: 'score',
transform: numberAttribute,
});
}Here the parent writes score="4". The static attribute arrives as the string "4", numberAttribute converts it to a number, and the component reads value() as a number. The two type arguments of input.required<number, unknown> are the type the component reads and the type the parent may pass.
Why you would alias an input
Aliases are not free. They give a component two vocabularies, and anyone reading the class has to map one to the other. These are the cases where that cost is worth paying.
Keeping a stable public API during a rename
The public name is a contract with every parent template. The field name is an implementation detail. If you want to rename the field, an alias lets you do it without touching any parent:
// Before
text = input('', { alias: 'label' });
// After: the field is renamed, and parents still write label="..."
caption = input('', { alias: 'label' });Only the component's own template and class need editing. This also holds when you migrate from @Input('label') text to input('', { alias: 'label' }), which Chapter 13 covers.
Avoiding a clash inside the class
A field name sometimes collides with something else in the class, such as a method, a computed value, or an inherited member. Suppose a component wants a public input called disabled but also has a disabled computed value that combines several conditions. Give the input a different field name and alias it:
import { Component, computed, input, booleanAttribute } from '@angular/core';
@Component({
selector: 'app-submit',
template: `<button [disabled]="disabled()">Send</button>`,
})
export class Submit {
disabledInput = input(false, { alias: 'disabled', transform: booleanAttribute });
busy = input(false, { transform: booleanAttribute });
disabled = computed(() => this.disabledInput() || this.busy());
}The parent writes <app-submit disabled />. Inside the class, disabledInput is the raw value and disabled is the effective one.
Matching a directive's selector
An attribute directive often takes one main value, and it reads best when the attribute name and the input name are the same. Aliasing the input to the selector achieves that:
import { Directive, ElementRef, effect, inject, input } from '@angular/core';
@Directive({ selector: '[appHighlight]' })
export class Highlight {
color = input('yellow', { alias: 'appHighlight' });
private el = inject<ElementRef<HTMLElement>>(ElementRef);
constructor() {
effect(() => {
this.el.nativeElement.style.backgroundColor = this.color();
});
}
}A parent can then write <p appHighlight="orange"> or <p [appHighlight]="theme.accent">. The same name selects the directive and supplies its value. Built-in directives such as ngClass follow this pattern. Note that a bare <p appHighlight> passes an empty string, not the default 'yellow', because the attribute is present with no value. If that matters, treat '' as "use the default" inside the directive.
Using an HTML-friendly or domain name
A field called isDisabled reads well in TypeScript, while disabled matches the HTML convention that parents expect. Aliasing lets each side use its own preferred name. Use this sparingly. The point is to match an established convention, not to invent a second name.
Rules and limits
- The alias must be a string literal. The Angular compiler reads it statically.
alias: someConstantor an expression built at runtime is rejected, even if the value would be known when the code runs. - Public names must be unique within a component. Two inputs with the same public name conflict. An input and an output may share a name only by accident, and you should avoid it.
- The alias is the name for everything outside the class. That includes templates,
setInput()on aComponentRef, and host-directive input lists. The field name is only for code inside the class. - The alias does not change the type or the behavior. Required checks, transforms, and signal reads all work as before. A missing required input is reported under its public name.
The testing point is the one most often missed. When you set an input from a test, you use the public name:
import { TestBed } from '@angular/core/testing';
import { IconButton } from './icon-button';
describe('IconButton', () => {
it('shows the label', async () => {
const fixture = TestBed.createComponent(IconButton);
fixture.componentRef.setInput('label', 'Save');
await fixture.whenStable();
expect(fixture.nativeElement.textContent).toContain('Save');
});
});Calling setInput('text', 'Save') would fail, because text is not a public input name.
Guidelines for using aliases
Prefer no alias. When the field name and the public name match, a reader can search the codebase for one name and find the declaration, the bindings, and the tests. Each alias breaks that link.
Add an alias when it solves a specific problem: protecting a public API during a rename, resolving a collision, or matching a directive selector. When you do, put a short comment next to it if the reason is not obvious from the names.
Do not alias just to make a name shorter in the template. Choose a good name for the field instead. Do not give an input a public name that differs from its purpose, such as exposing label as title for no reason. Parents then have two vocabularies to remember for one component.
Common mistakes
- Binding to the field name. After adding
alias: 'label',[text]no longer works. Search parent templates and tests for the old name when you add an alias to an existing input. - Putting the alias in the wrong argument.
input({ alias: 'label' })treats the object as the initial value. Pass the default first:input('', { alias: 'label' }). For a required input, no default is passed:input.required<string>({ alias: 'label' }). - Computing the alias. A variable or template string for
aliasfails to compile. Use a literal. - Forgetting that
model()renames the output too. Withalias: 'on', listening to(checkedChange)stops working. The event is(onChange). - Testing with the field name.
setInput()expects the public name.
Exercise
A component declares value = input.required<number>({ alias: 'score' }). A parent template contains <app-rating [value]="4" />. What happens, and how do you fix it?
Show answer
The build fails, because value is the field name and the public input is score. Angular reports that value is not a known property of the component. Change the parent to <app-rating [score]="4" />. Inside the component, the code still reads this.value().
Exercise
You have checked = model(false, { alias: 'on' }). Write the parent template line that binds it two ways to a parent property isOn, and name the output event the child emits.
Show answer
The template line is <app-toggle [(on)]="isOn" />. The child emits the output onChange, which is the alias plus Change. The two-way shorthand [(on)] expands to [on]="isOn" (onChange)="isOn = $event".