How are directives related to DOM elements?
In Angular, directives are bound to DOM elements through a selector:
- When Angular renders a template, it looks for elements matching the directives' selectors.
- Angular then creates an instance of the directive and links it to that element.
- The directive can change the element's properties, styles, classes and attributes, listen for events or control its structure (for structural directives).
ElementRefandRenderer2are often used to interact with the element and safely modify the DOM.
Example:
html
<p appHighlight>Text</p>- The
appHighlightdirective is bound to<p>. - Its constructor can use
ElementRefto change the background, color, class and so on.
Conclusion: directives are "wrappers" around DOM elements that let Angular control their behavior and appearance.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.