Question presented to candidate: "Build a toggle directive that adds a class and an aria attribute to its element when clicked and resets on Escape anywhere on the page. Show it with @HostListener and @HostBinding, then tell me what the Angular docs recommend instead today."
What a strong answer should cover:
- Host element: the element a directive or component is attached to; host bindings change it, host listeners listen on it.
@HostBinding('class.on'),'attr.aria-pressed','style.width.px', plain properties;@HostListener('click', ['$event']), global targetsdocument:/window:, key filters likekeydown.escape.- A
@HostListenerhandler that returnsfalsecallspreventDefault(); anullattribute binding removes the attribute. - The 22.2.3 typings say to always prefer the
hostproperty in@Component/@Directivemetadata; the decorators exist for backwards compatibility. - Both forms compile to the same host-binding instructions, and host expressions are type-checked with strict templates.
- With signals in the
hostbindings, OnPush and zoneless are handled naturally.
Clarifying questions expected:
- "Should Escape be listened for on the document, or only while the element has focus?"
- "Is this a directive on existing elements, or a component styling its own host?"
Code / implementation expected: Yes — the same directive written once with decorators and once with host metadata.