Lesson 8

Using ElementRef and Renderer

How to update elements the Angular way

PRO

Lesson Outline

Using ElementRef and Renderer

There may come a time where we want to make a change to the host DOM element for our component, or to any other element. Perhaps we want to change the style of an element, add a class, changes its text, or something else.

We can grab a reference to the host element of a component by using ElementRef which can be imported from the Angular core library:

import { Component, ElementRef } from '@angular/core';

All we need to do is inject this into the constructor for the class of the component:

constructor(private element: ElementRef) {

}

and then an ElementRef for that particular component will be available through this.element - we can also use this same method inside of a directive to grab a reference to the element that the directive is attached to. As well as getting a reference to the host element, we can also get a reference to any other element in the template by using @ViewChild or @ContentChild but we will be covering those concepts a little later.

The role of ElementRef is to provide us with direct access to the DOM element, which will be available through a property called nativeElement. If we wanted to access the DOM element given the example above, we could access this.element.nativeElement.

Once we have a reference to that DOM element, we could modify it in any way we like by directly accessing its properties (as you would with vanilla JavaScript). For example, if we wanted to access the elements background colour we could do so using:

PRO

Thanks for checking out the preview of this lesson!

You do not have the appropriate membership to view the full lesson. If you would like full access to this module you can view membership options (or log in if you are already have an appropriate membership).