import { bootstrapApplication } from '@angular/platform-browser';
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
styles: [`
.panel { padding: 12px; border: 1px solid #ccc; border-radius: 6px; }
.row { display: grid; grid-template-columns: 1fr auto; gap: 8px; align-items: center; }
input { padding: 6px 8px; }
`],
template: `
<h3>ViewChild & AfterViewInit</h3>
<div #panel class="panel">
<div class="row">
<input #box type="text" placeholder="Focused after view init" />
<button (click)="measure()">Measure</button>
</div>
<p>Panel size: {{ size }}</p>
</div>
`
})
export class App implements AfterViewInit {
@ViewChild('box') box; // ElementRef<HTMLInputElement>
@ViewChild('panel') panel; // ElementRef<HTMLDivElement>
size = '';
ngAfterViewInit() {
// Focus input once view is initialized, then measure panel
setTimeout(() => {
this.box?.nativeElement?.focus?.();
this.measure();
});
}
measure() {
const el = this.panel?.nativeElement;
if (!el) return;
const rect = el.getBoundingClientRect();
this.size = `${Math.round(rect.width)}×${Math.round(rect.height)}`;
}
}
bootstrapApplication(App);
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Angular Lifecycle - ViewChild & AfterViewInit</title>
</head>
<body>
<app-root></app-root>
</body>
</html>