
Inputs Aren't Ready in the Constructor: constructor vs ngOnInit
- كاتب موثّق
- Angular 22
محتويات المقال
this.productId() in its constructor to start loading the product. A teammate "fixes" it by switching back to @Input() productId!: string. The error disappears, and the network tab now shows a request for /api/products/undefined.
The common misconception
inject(ProductApi) works in a field initializer, and older code received services as constructor parameters. If the dependencies are there, why wouldn't the inputs be? The difference is where each one comes from. Services come from the injector, which Angular asks while it builds the instance. Inputs come from the parent's template, and Angular can only apply them to an instance that already exists.
What actually happens
Create first, bind second
<app-product-details [productId]="id" />, Angular sets up the component in a fixed order:
It calls the constructor. Field initializers run as part of construction, so inject()calls andinput()declarations are evaluated here.It sets each input from the parent's bindings. It can't do that earlier: there's no object to set them on until the constructor returns. It calls ngOnChangeswith the first values, if the component defines it.It calls ngOnInit, exactly once, before the component's own template is initialized.
What an early read gives you
input.required() throws NG0950, because there's no value and no default to fall back on. An input('') returns '', its default. A decorator-based @Input() field is undefined, or whatever its initializer set. Only the first one fails loudly. The other two let your code carry on with the wrong value, which is how undefined ends up in a URL.
import { Component, inject, input, signal } from '@angular/core';@Component({ selector: 'app-product-details', template: `<h2>{{ product()?.name }}</h2>`,})export class ProductDetails { private readonly api = inject(ProductApi); // fine: DI is ready readonly productId = input.required<string>(); readonly product = signal<Product | undefined>(undefined); constructor() { // NG0950: the parent hasn't bound productId yet this.api.get(this.productId()).then((p) => this.product.set(p)); }}import { Component, OnInit, inject, input, signal } from '@angular/core';@Component({ selector: 'app-product-details', template: `<h2>{{ product()?.name }}</h2>`,})export class ProductDetails implements OnInit { private readonly api = inject(ProductApi); readonly productId = input.required<string>(); readonly product = signal<Product | undefined>(undefined); ngOnInit(): void { // Inputs hold the parent's first values here this.api.get(this.productId()).then((p) => this.product.set(p)); }}ngOnInit runs after step 2, so productId() holds the parent's value. The inject() call stays where it was: field initializers and the constructor are the component's , so dependencies are ready there even though inputs aren't.
ngOnInit runs once; inputs keep changing
ngOnInit is a that runs exactly once, but a parent can change a binding at any time: think of a product list where the user clicks a different row. The input updates, the template re-renders whatever reads it, and the product loaded in ngOnInit stays the first one. The classic answer was ngOnChanges: check whether productId is among the changes and reload. It works, but every input that matters needs its own branch, and cancelling the previous request is up to you. With signal inputs, you don't have to pick a moment at all. Read the input inside something reactive:
import { Component, inject, input, resource } from '@angular/core';@Component({ selector: 'app-product-details', template: ` @if (product.hasValue()) { <h2>{{ product.value().name }}</h2> } `,})export class ProductDetails { private readonly api = inject(ProductApi); readonly productId = input.required<string>(); // Loads after inputs are set, and again whenever productId changes readonly product = resource({ params: () => ({ id: this.productId() }), loader: ({ params, abortSignal }) => this.api.get(params.id, abortSignal), });}resource() evaluates params lazily, after the inputs are set, and again whenever productId changes. It then calls the loader with the new value and aborts a load that's still running for the old one. A plain derived value, like a URL or a label, needs even less: computed(() => ...) reads the input when it's first used and recomputes when the input changes. The NG0950 docs name exactly these safe places: the template, a computed(), an effect, or ngOnInit and later.
input.required(); the default for input() and @Input() | ||
ngOnChanges | ||
ngOnInit | ||
computed(), effect, resource() params |
How to apply it in your project
Search constructors for input reads Look for input reads in constructors and field initializers: this.someInput()calls and@Input()fields. Each one is a bug, loud or silent.Move one-time setup to ngOnInit If the work only needs the first value, like logging which product was opened, move it to ngOnInit.Make data that depends on inputs reactive Derive values with computed()and load data with aresource()keyed on the input, so a changed binding reloads.Prefer input.required() for essential inputs A required input fails with NG0950 when it's read too early, instead of quietly returning a default.
Key takeaways
Angular constructs the component, then sets its inputs, then calls ngOnChangesandngOnInit.In the constructor, input.required()throws NG0950; optional and@Input()inputs quietly return defaults.The constructor is the injection context: use it for inject(),effect()and wiring, not for input-based work.ngOnInitsees the first input values, once;computed()andresource()follow every change.
التعليقات (0)