Getting into attribute directives with Renderer2
Sometimes a component feels like too much, when all you want is one small behavior on an element. Like, make a button glow on hover, add a class when something is active, or set an aria label without touching the template every time. That is where an attribute directive fits. It sits on an existing element and quietly changes how it looks or reacts.
But changing the DOM directly can get messy. You might reach for nativeElement and start setting styles and classes by hand. It works, until it doesn’t. Different platforms, server side rendering, tests, and even future Angular changes can make direct DOM access feel risky.
Renderer2 is the safer tool for this job. With it, we can add classes, set styles, update attributes, and listen to events in a way Angular likes. And when we are done listening or changing things, we also clean up properly so nothing keeps running in the background.
A small ending
If we build the directive step by step, it starts simple and then grows into something reliable. First we change one thing on the element. Then we react to user actions. Then we remember to remove listeners and reset stuff when needed.