angular-viewchild
Installation
SKILL.md
Angular ViewChild / ContentChild
Version: Angular 21 (2025) Tags: ViewChild, ContentChild, DOM, Queries
References: ViewChild API • ContentChild API
Best Practices
- Use ViewChild for element reference
import { ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({})
export class MyComponent implements AfterViewInit {
@ViewChild('input') inputEl!: ElementRef<HTMLInputElement>;
ngAfterViewInit() {
this.inputEl.nativeElement.focus();
}
}
- Use static option
// Static - available in ngOnInit
@ViewChild('static', { static: true }) staticEl!: ElementRef;
// Dynamic - available in ngAfterViewInit
@ViewChild('dynamic', { static: false }) dynamicEl!: ElementRef;
- Use ContentChild for projected content
import { ContentChild, TemplateRef } from '@angular/core';
@Component({
selector: 'app-card',
template: `
<div class="card">
<ng-content></ng-content>
</div>
`
})
export class CardComponent {
@ContentChild(TemplateRef) headerTemplate!: TemplateRef<any>;
}
- Use ViewChildren for multiple elements
import { ViewChildren, QueryList } from '@angular/core';
@Component({})
export class ListComponent {
@ViewChildren('item') items!: QueryList<ElementRef>;
ngAfterViewInit() {
this.items.forEach(item => console.log(item));
}
}
- Use read option
@ViewChild('component', { read: ViewContainerRef }) container!: ViewContainerRef;
@ViewChild('template', { read: TemplateRef }) template!: TemplateRef<any>;
- Access component instance
@ViewChild(ChildComponent) child!: ChildComponent;
ngAfterViewInit() {
this.child.doSomething();
}
- Use with signals
@ViewChild('el') el!: ElementRef<HTMLElement>;
ngAfterViewInit() {
effect(() => {
if (this.shouldFocus()) {
this.el.nativeElement.focus();
}
});
}
Related skills
More from oguzhan18/angular-ecosystem-skills
angular-tailwind
ALWAYS use when working with Angular and Tailwind CSS, Tailwind configuration, utility-first CSS, or styling Angular applications with Tailwind.
139angular-animations
>-
137rxjs
ALWAYS use when working with RxJS Observables, operators, and reactive patterns in Angular applications.
135angular-material
ALWAYS use when working with Angular Material components, CDK, or Material Design in Angular applications.
131angular-security
ALWAYS use when working with Angular Security, XSS prevention, CSRF protection, Content Security Policy, or sanitization in Angular applications.
130angular-bootstrap
ALWAYS use when working with Angular Bootstrap, ng-bootstrap, Bootstrap components in Angular, or Bootstrap 5 integration.
129