DEV Community

Cover image for Angular 10/9 ViewChild, ElementRef & AfterViewInit
Ahmed Bouchefra
Ahmed Bouchefra

Posted on

3 2

Angular 10/9 ViewChild, ElementRef & AfterViewInit

In this article, we'll see how to use ElementRef, ViewChild decorator, and AfterViewInit life-cycle event for accessing the DOM by example with Angular 10:

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';
  isDisplayed = false;

  @ViewChild("myimg") elementView: ElementRef;

  ngOnInit(){
    this.isDisplayed=true;
  }

  ngAfterViewInit(){
    console.log(this.elementView);
    console.log("client height: " + this.elementView.nativeElement.clientHeight);
    console.log("client width: "+ this.elementView.nativeElement.clientWidth);
  }
}
Enter fullscreen mode Exit fullscreen mode

Run the example https://stackblitz.com/edit/angular-10-viewchild-elementref-ngafterviewinit-example

Learn Angular with techiediaries.com

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay