Here we have a very simple directive, which when applied to an element, we would like to style that element with some properties. As a first step we simply go onto our HTML part here and we add that style tag. With this we basically apply our directive onto that div here.
As a next step, within that directive we need to get hold of this div here in order that we can add some styles. We can do that as a first step by importing element ref always from Angular Core. Then in the constructor, we can get that element ref injected.
As a next step, that element ref has an API which allows us to access the native element, which is actually the underlying dom element. From here on, we can use the native HTML API to style that backgroundColor=yellow. If we save this, we see how the style gets applied to our element.
As you can see, this works perfectly. However, it should be avoided to directly access the native element here, because Angular is designed to run also in environments where we actually don't have a DOM API. For instance, on the server side or when rendered within a Web Worker.
Let's comment that part out for a second. Instead, we can use a more abstract object, which is called the Renderer2, which you can import. Now we get it injected here. The Renderer allows us to have a more abstract API, so we can do something like setStyle. We pass in the element, which we get from the element ref of nativeElement.
Then we define the style, which in our case is the background color and we give it a value, which is yellow. We can save. We can see how that style gets applied again. This makes our code much more safe for non-DOM API environments, because the Renderer and the setStyle method basically abstracts the environment from the actual logical one to apply.