Question presented to candidate: "You have a list of item components rendered with @for. When would you use @ViewChild and when @ViewChildren to reach them, what type does each give you, and how do you react when items are added or removed?"
What a strong answer should cover:
@ViewChildreturns the first match (orundefined);@ViewChildrenreturns all matches as aQueryList.- QueryList:
length,first,last,toArray(),forEach/map/filter, and thechangesobservable that emits when the set of matches changes. - Both are live for dynamic (
@if/@for) content and are first ready inngAfterViewInit; only@ViewChildhas astaticoption (passing it to@ViewChildrenis a type error). - Same locators and
readoption for both; under the hood@ViewChildis the same query with.firsttaken. - Subscribe to
changesinngAfterViewInitand clean up; with signal queries,viewChildren()returns a signal of a readonly array instead. - Do not keep a stale reference to
first: it can change as items are added or removed.
Clarifying questions expected:
- "Do I need the component instances or the DOM elements?"
- "Can the list change at runtime, or is it fixed?"
Code / implementation expected: Yes — a list where one button acts on the @ViewChild result and another on every @ViewChildren result.