Question presented to candidate:
"A dashboard lets users add widgets whose type is only known at runtime, and a toast service needs to show a component attached to document.body. How do you create components dynamically in modern Angular, pass them inputs and listen to their outputs?"
What a strong answer should cover:
ViewContainerRef.createComponent(Type)inserts a component at an anchor (often<ng-container #slot>read as aViewContainerRef) and returns aComponentRef.- Pass inputs with
ref.setInput(name, value)(marks OnPush views dirty) or, since v20, declarebindings: [inputBinding(...), outputBinding(...), twoWayBinding(...)]at creation; signals bound this way stay live. - Clean up with
ref.destroy()orcontainer.clear(); subscriptions to outputs end with the component. NgComponentOutlet(*ngComponentOutlet="type; inputs: {...}") is the declarative option for "render whichever component this signal holds".- The standalone
createComponent()function withenvironmentInjectorandhostElementcreates a component outside any container; you mustappRef.attachView(ref.hostView)for it to update. ComponentFactoryResolveris gone from the v22 public API; the component class is passed directly.
Clarifying questions expected:
- "Does the component need to live inside the current view, or at
document.bodylike an overlay?" - "Are the components known at build time, or lazy-loaded (
import()), for example from a remote?"
Code / implementation expected: Yes β a container-based example with setInput and NgComponentOutlet, plus one using bindings and the standalone createComponent().