loading...
Cover image for Angular 10/9 ViewChild, ElementRef & AfterViewInit

Angular 10/9 ViewChild, ElementRef & AfterViewInit

techiediaries profile image Ahmed Bouchefra ・1 min read

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);
  }
}

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

Learn Angular with techiediaries.com

Posted on by:

techiediaries profile

Ahmed Bouchefra

@techiediaries

I write about modern frontend and backend technologies.

Discussion

markdown guide