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
Top comments (0)