Question presented to candidate: "An event-booking form lets the user add any number of guests, each with a name and a meal choice, and remove them again. What is a FormArray, and how would you build this with it?"
What a strong answer should cover:
- A
FormArrayis a reactive-forms container that holds an ordered list of controls addressed by index, for repeating fields whose count is not known up front. - Items can be
FormControls or wholeFormGroups; the array'svalueis an array of their values, and its status aggregates the children (one invalid row makes the array invalid). - Mutation API:
push,insert,removeAt(accepts negative indexes),setControl,clear,at,length. - Template wiring:
formArrayNameon a wrapper,[formGroupName]="i"per row, rendered with@forand a stabletrack(the control object). - Typed arrays (
FormArray<FormGroup<{...}>>), plus validating the list itself:Validators.requiredmeans "at least one item", whileValidators.minLength(1)does not catch an empty array. - Contrast with
FormGroup(fixed named keys) andFormRecord(dynamic string keys).
Clarifying questions expected:
- "Is there a minimum or maximum number of guests?"
- "Do rows need stable identity, for example to keep focus or animations when one in the middle is removed?"
Code / implementation expected: Yes β a FormArray of FormGroups with add and remove buttons, showing the value after each change.