DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

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

Posted on

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

Top comments (0)

🌚 Life is too short to browse without dark mode