Skip to main content

How are directives related to DOM elements?

In Angular, directives are bound to DOM elements through a selector:

  1. When Angular renders a template, it looks for elements matching the directives' selectors.
  2. Angular then creates an instance of the directive and links it to that element.
  3. The directive can change the element's properties, styles, classes and attributes, listen for events or control its structure (for structural directives).
  4. ElementRef and Renderer2 are often used to interact with the element and safely modify the DOM.

Example:

html
<p appHighlight>Text</p>
  • The appHighlight directive is bound to <p>.
  • Its constructor can use ElementRef to 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.