Question presented to candidate: "A teammate wrote a directive that calls document.createElement and element.style directly. In review you suggest Renderer2. Justify it: what concrete problems does Renderer2 solve, what does it NOT solve, and when would you avoid both?"
What a strong answer should cover:
- Renderer2 is Angular's abstraction over DOM operations (
createElement,appendChild,addClass,setStyle,setAttribute,setProperty,listen), injected per component. - Platform independence: on the server there is no global
document(aReferenceError); Renderer2 andinject(DOCUMENT)work in SSR. - Encapsulation: elements created through the component's Renderer2 get the emulated-encapsulation attribute, so component styles apply;
document.createElementdoes not. listen()returns an unlisten function; tie it toDestroyRef.- It is not a security layer: the 22.2.3 typings say it provides no extra security, and
setProperty(el, 'innerHTML', ...)is not sanitised. - Best of all: avoid imperative DOM work entirely with bindings /
hostmetadata, and run browser-only work inafterNextRender.
Clarifying questions expected:
- "Does the app use SSR or prerendering?"
- "Is the DOM change expressible as a binding instead?"
Code / implementation expected: Yes β a directive that adds a class, a style, an attribute, a created child element and a listener through Renderer2, with cleanup.