Question presented to candidate:
"A component loads a user by an id input. Should that code go in the constructor or in ngOnInit, and what actually differs between the two?"
What a strong answer should cover:
- The constructor is plain TypeScript: Angular calls it to create the instance; use it (or field initialisers) for dependency injection and simple setup.
- Inputs are not set yet in the constructor: decorator inputs hold their defaults; reading a required signal input throws NG0950 (and AOT flags it as NG8118).
ngOnInitis a lifecycle hook Angular calls once, after the firstngOnChanges, when inputs have their first values.ngOnInitruns once: if the input changes later, code there does not re-run (ngOnChanges,computedoreffecthandle changes).- With signal inputs, derived state is often a
computedin a field rather than code inngOnInit. - The constructor is the injection context (
inject()works there);ngOnInitis not.
Clarifying questions expected:
- "Are the inputs decorator inputs or signal inputs?"
- "Can the id change while the component stays on screen?"
Code / implementation expected: Yes β log the order of constructor, ngOnChanges and ngOnInit, and show a value that goes stale.