In this tutorial, we’ll see how to use ElementRef
, ViewChild
decorator, and AfterViewInit
life-cycle event for accessing the DOM by example with Angular 10.
ViewChild
and AfterViewInit
?You can use ViewChild
if you need to access a child component, directive or a DOM element from an Angular parent component.
The ViewChild
decorator is the way you can achieve DOM access in Angular way. ViewChild
returns the first element that matches a given component, directive or template reference selector.
You can also have access to multiple children using ViewChildren
instead.
We can access the following elements:
AfterViewInit
is a life-cycle hook that gets fired when the view corresponding to the component is completely rendered. This can be used to safely access the variables, directives, and child components.
ElementRef
?Although you can access the DOM using native JavaScript APIs in Angular, it’s recommended to use APIs provided by Angular. We can access the DOM elements by using ElementRef
available from by @angular/core
.
ElementRef
allows you to access the native DOM element using the nativeElement
property. But you need to be careful when making direct DOM access in Angular.
According to Angular docs ElementRef
:
__Use this API as the last resort when direct access to DOM is needed. Permitting direct access to the DOM can make your application more vulnerable to XSS attacks.Carefully review any use of ElementRef in your code. Use templating and data-binding provided by Angular instead. Alternatively you take a look at _
_Renderer_
which provides API that can safely be used even when direct access to native elements is not supported.
Relying on direct DOM access creates tight coupling between your application and rendering layers which will make it impossible to separate the two and deploy your application into a web worker.
Not good. But, there’s an alternative called
_Renderer2_
.
ElementRef
and ViewChild
by ExampleLet’s see how to use ElementRef
and ViewChild
by example.
Let’s get started by an example of to access a native DOM elements which has a template reference variable.
Open the src/app/app.component.ts
file and update it as follows:
import { Component, AfterViewInit, OnInit, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit, OnInit {
name = 'Angular';
@ViewChild("myimg") elm: ElementRef;
ngOnInit(){}
ngAfterViewInit(){
console.log(this.elm);
}
}
#angular #elementref #viewchild #afterviewinit #angular 10