Sub topic 4
Making an Input Required
This chapter assumes you can read a signal by calling it, know how input() declares an optional input, and can write property bindings in a standalone component's template. It covers input.required(): what it guarantees, what it costs, how it combines with other options, and where it fails at runtime.
Why some inputs should not be optional
Some components cannot do their job without a value from the parent. A user card with no user, or a chart with no data series, is a bug in the parent's template and not a state worth rendering.
input() with no default forces you to model "not provided". The signal's type becomes T | undefined, and every read has to handle it:
name = input<string>(); // InputSignal<string | undefined>input.required() removes that case from the type and moves the check to build time:
name = input.required<string>(); // InputSignal<string>The child can then use this.name() as a plain string. The compiler makes sure every parent supplies the value.
Declaring a required input
Call input.required<T>() with a type argument. It takes no default value, because a default would mean the input is never missing.
import { Component, input } from '@angular/core';
@Component({
selector: 'app-user-card',
template: `
<h2>{{ name() }}</h2>
<p>Role: {{ role() }}</p>
`,
})
export class UserCard {
name = input.required<string>();
role = input('guest');
}Here name must always be supplied, and role falls back to 'guest'. The type argument is needed because there is no initial value to infer from.
What the parent must do
A required input counts as supplied if the parent uses any binding form that targets it. A property binding works, and so does a static attribute:
<app-user-card [name]="user.name" />
<app-user-card name="Ada" role="admin" />If the parent leaves it out, the Angular compiler reports an error such as Required input 'name' from component UserCard must be specified. The same diagnostic shows up in your editor through the Angular language service.
<!-- Compile error: name is required -->
<app-user-card role="admin" />Supplying a value does not mean supplying a good value
The check only looks at whether a binding exists. It does not check that the bound expression has a value at runtime. If user.name evaluates to undefined while the type says string, nothing stops it. Under strictTemplates, the type checker rejects a binding whose static type cannot be assigned to string, such as [name]="maybeUser?.name" when that expression is string | undefined. This is one reason to enable strictTemplates in the project.
Required versus optional: choosing
| Question | Optional `input()` | `input.required()` | Column |
|---|---|---|---|
| Can the parent omit it? | Yes | No, compile error | |
| Type of the value | `T`, or `T \ | undefined` without a default | `T` |
| Has a default? | Yes, if you give one | Never | |
| Right for | Configuration, styling variants, flags | The data the component exists to show |
A useful rule is to ask whether the component makes sense with the input missing. If a sensible default exists, such as 'guest', 16, or false, use an optional input. If the only default you could invent is a fake placeholder like '' or 0, make the input required. Placeholder defaults hide bugs, because the component renders without complaint and shows wrong output.
Combining required with alias and transform
input.required() accepts the same options object as input(), apart from the default value, which does not exist. You can set alias and transform on a required input.
import { Component, input, numberAttribute } from '@angular/core';
@Component({
selector: 'app-progress',
template: `<progress [value]="percent()" max="100"></progress>`,
})
export class Progress {
percent = input.required<number, unknown>({
alias: 'value',
transform: numberAttribute,
});
}The parent writes <app-progress value="40" />. The attribute string "40" is converted to the number 40 by the transform, and the alias value is the public name. The required check applies to the public name, so the compile error would say value is missing. Two type arguments are used because a transform has an input type (unknown, what the parent may pass) and a stored type (number, what the child reads).
Deriving state from a required input
Because the value is never undefined, computed() code stays free of null checks:
import { Component, computed, input } from '@angular/core';
@Component({
selector: 'app-avatar',
template: `<span class="avatar">{{ initials() }}</span>`,
})
export class Avatar {
name = input.required<string>();
initials = computed(() =>
this.name()
.split(' ')
.map((part) => part[0])
.join('')
);
}initials runs lazily. It first executes when the template reads it, which happens after Angular has set the inputs. That ordering is why computed() is safe here, and it leads to the main runtime failure.
The runtime error: reading too early
The compile-time check guarantees the parent supplied a binding. It does not guarantee the value has arrived at every point in the child's lifecycle. Angular sets inputs after it constructs the component. If you read a required input while the class is still being constructed, there is no value yet, and Angular throws:
NG0950: Input is required but no value is available yet.The usual causes are field initializers and constructors that read the input directly:
import { Component, input } from '@angular/core';
@Component({
selector: 'app-broken',
template: `{{ upper }}`,
})
export class Broken {
name = input.required<string>();
upper = this.name().toUpperCase(); // throws NG0950 during construction
}The fix is to defer the read. A computed() delays it until first use:
import { Component, computed, input } from '@angular/core';
@Component({
selector: 'app-fixed',
template: `{{ upper() }}`,
})
export class Fixed {
name = input.required<string>();
upper = computed(() => this.name().toUpperCase());
}Other safe places to read the input are ngOnInit() and later lifecycle hooks, effect() callbacks, and event handlers.
Required inputs in tests
Tests are the other common place to hit NG0950. If you create a component with TestBed.createComponent() and run change detection without setting its required inputs, the template read throws. Set inputs through the component ref before the first detectChanges():
import { TestBed } from '@angular/core/testing';
import { UserCard } from './user-card';
describe('UserCard', () => {
it('renders the name', () => {
const fixture = TestBed.createComponent(UserCard);
fixture.componentRef.setInput('name', 'Ada');
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('h2').textContent).toBe('Ada');
});
});Assigning fixture.componentInstance.name = ... does not work, because the input is a read-only signal and not a property you can overwrite. setInput() is the supported way, and it also works for optional inputs.
Edge cases and common mistakes
- Writing to the input. Signal inputs are read-only inside the child.
this.name.set('x')is a compile error. If the child needs to change the value and tell the parent, usemodel(), which a later chapter covers. - Expecting a default.
input.required<string>('guest')is not valid. Pickinput('guest')instead. - Forgetting the type argument. Without a value to infer from,
input.required()gives youunknown. Always writeinput.required<T>(). - Using
T | undefinedto "make it required".input.required<string | undefined>()forces the parent to bind the input, but the bound value may be undefined. This is a valid choice when "the parent must make a decision, even if the answer is nothing". Make that choice on purpose. - Dynamic creation. Components created in code, for example with
createComponent(), bypass template checking. The compiler cannot warn you about a missing required input there, so set every required input yourself withsetInput()before the first change detection.
Exercise
A component declares title = input.required<string>(); and also has the field shout = this.title().toUpperCase();. The parent passes title="Hello" correctly, and the project compiles. What happens at runtime, and how do you fix it?
Show answer
Angular throws NG0950 ("Input is required but no value is available yet") when it constructs the component, because field initializers run before inputs are set. The compile-time check only confirms that the parent bound the input. To fix it, make the derived value lazy: shout = computed(() => this.title().toUpperCase()); and read it as shout() in the template.
Exercise
You have size = input(16, { transform: numberAttribute }); and decide the parent must always provide the size. Write the new declaration, keeping the string-to-number conversion.
Show answer
size = input.required<number, unknown>({ transform: numberAttribute }); The default value 16 is removed because required inputs cannot have one. The first type argument is the type the child reads (number) and the second is the type the parent may pass (unknown).