Using ElementRef and Renderer
How to update elements the Angular way
PROModule Outline
- Source Code & Resources PRO
- Lesson 1: Introduction PUBLIC
- Lesson 2: The Role of Components and Directives PUBLIC
- Lesson 3: When to Use Custom Components & Directives PRO
- Lesson 4: Building a Simple Component PRO
- Lesson 5: Building a Simple Directive PRO
- Lesson 6: Setting up Components and Directives PRO
- Lesson 7: Using @Input and @Output PRO
- Lesson 8: Using ElementRef and Renderer PRO
- Lesson 9: Understanding Content Projection PRO
- Lesson 10: Understanding @ViewChild and @ContentChild PRO
- Lesson 11: Building a Complex Component PRO
- Lesson 12: Listening for Events and Binding to Properties PRO
- Lesson 13: Building a Skeleton Card Component PRO
- Lesson 14: Creating an Autogrow Directive for a Textarea PRO
- Lesson 15: Handling Error Messages with a Custom Component PRO
- Lesson 16: Building a Parallax Header Directive PRO
- Lesson 17: High Performance Accordion Component PRO
- Lesson 18: Conclusion 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:
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).