الانتقال إلى المحتوى
FrontendAngular· 7 دقائق للقراءة

Inputs Aren't Ready in the Constructor: constructor vs ngOnInit

Angular creates the component first and binds its inputs second. Where you read an input decides what you get.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • Angular 22
محتويات المقال

A product page crashes the moment it opens with NG0950, Angular's error for a required input that was read before it had a value. The component calls 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

The belief: by the time the constructor runs, the component is fully configured, inputs included, so it's the natural place to start work that depends on them.

That's how classes work everywhere else: the constructor receives what the object needs, and the object is ready when it returns. Developers coming from React expect the same, since a function component gets its props as an argument and can use them on its first line. Angular seems to confirm it, because services really are ready there. 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

When a parent's template contains <app-product-details [productId]="id" />, Angular sets up the component in a fixed order:

  1. It calls the constructor. Field initializers run as part of construction, so inject() calls and input() declarations are evaluated here.
  2. 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.
  3. It calls ngOnChanges with the first values, if the component defines it.
  4. It calls ngOnInit, exactly once, before the component's own template is initialized.

What an early read gives you

The constructor runs before step 2, and what it sees depends on how the input is declared. An 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.

TypeScript product-details.ts
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));  }}

In the fixed version, 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

That fix has a limit. 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:

TypeScript product-details.ts
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.

Where you read the inputWhat you getFollows later changes?
Constructor or field initializerNG0950 for input.required(); the default for input() and @Input()No
ngOnChangesPrevious and current values of the inputs that changedYes, runs on every change
ngOnInitThe parent's first valuesNo, runs once
Template, computed(), effect, resource() paramsThe current valueYes, tracked automatically

How to apply it in your project

  1. Search constructors for input readsLook for input reads in constructors and field initializers: this.someInput() calls and @Input() fields. Each one is a bug, loud or silent.
  2. Move one-time setup to ngOnInitIf the work only needs the first value, like logging which product was opened, move it to ngOnInit.
  3. Make data that depends on inputs reactiveDerive values with computed() and load data with a resource() keyed on the input, so a changed binding reloads.
  4. Prefer input.required() for essential inputsA 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 ngOnChanges and ngOnInit.
  • 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.
  • ngOnInit sees the first input values, once; computed() and resource() follow every change.

📚 المصادر

  1. Component lifecycle — Angular
  2. NG0950: Required input is accessed before a value is set — Angular
  3. Accepting data with input properties — Angular
  4. Async reactivity with resources — Angular
  5. Injection context — Angular

التعليقات (0)