Question presented to candidate: "We have a product list and a cart badge in different parts of the page. Neither is a parent of the other. How do you get data from one to the other in Angular, and how do you choose between the options?"
What a strong answer should cover:
- Default answer: a shared service holding state as signals, injected into both siblings with
inject(); expose read-only signals and methods for changes. - Scope matters:
providedIn: "root"gives one app-wide instance;providers: [...]on a common ancestor gives one instance per ancestor subtree. - Lifting state up to the nearest common parent with inputs, outputs or
model()works when the siblings are close. - RxJS alternative: a
BehaviorSubjectin the service (late subscribers get the current value; a plainSubjectdoes not). - Other channels: the router (URL and query params) for shareable state, a state library (NgRx, signal store) for large apps.
- Avoid: global variables, reaching into siblings through
ViewChildchains, or event buses with no ownership.
Clarifying questions expected:
- "Should this state survive navigation or a page refresh?"
- "Is there one instance of each sibling, or could the pair appear several times on a page?"
Code / implementation expected: Yes β a signal-based service shared by two sibling components.