Question presented to candidate: "Every custom form control in our codebase has this providers line: provide NG_VALUE_ACCESSOR, useExisting forwardRef, multi true. A junior developer asks what it actually does and whether they can delete parts of it. What do you tell them?"
What a strong answer should cover:
NG_VALUE_ACCESSORis an InjectionToken that forms directives (NgModel,FormControlDirective,FormControlName) inject from the same element to find the object implementingControlValueAccessor.multi: true: several directives on one element can contribute accessors (the built-inDefaultValueAccessoralso matches many elements); Angular collects them into an array and picks one: custom beats built-in beats default. Withoutmulti, Angular throwsNG01200.useExisting: reuse the component instance Angular already created, instead of constructing a second one (useClasswould).forwardRef: defers reading the class reference; it is the documented convention and needed when the class is referenced before its declaration is initialised. Verified: on 22.2.3 a self-reference in the class's own decorator also worked without it.- No provider at all:
NG01203: No value accessor for form control .... Two custom accessors on one element: "More than one custom value accessor matches". - Alternative: inject
NgControland setngControl.valueAccessor = this(no provider; providing both creates a circular dependency,NG0200). In v22,model()-based controls need no token.
Clarifying questions expected:
- "Does the component also need to display its own validation errors?"
- "Is it used with both reactive and template-driven forms?"
Code / implementation expected: Yes β the provider line explained, plus the NgControl-injection alternative.