Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Use the Renderer2 to add styles to an element in Angular

    Juri StrumpflohnerJuri Strumpflohner

    In this lesson we will go low-level and learn how you can get hold of the underlying native DOM element to add styling. Moreover we will learn how to make use of the Render2 to safely add style properties which even work in a server-side environment.

    angularAngular
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 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.

    00:19 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.

    00:44 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.

    01:07 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.

    01:22 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.

    01:49 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.

    Discuss

    Discuss