Loading...
Loading...
ALWAYS use when working with Angular ViewChild, ContentChild, ViewChildren, or accessing DOM elements and child components in Angular.
npx skill4agent add oguzhan18/angular-ecosystem-skills angular-viewchildimport { ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({})
export class MyComponent implements AfterViewInit {
@ViewChild('input') inputEl!: ElementRef<HTMLInputElement>;
ngAfterViewInit() {
this.inputEl.nativeElement.focus();
}
}// Static - available in ngOnInit
@ViewChild('static', { static: true }) staticEl!: ElementRef;
// Dynamic - available in ngAfterViewInit
@ViewChild('dynamic', { static: false }) dynamicEl!: ElementRef;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>;
}import { ViewChildren, QueryList } from '@angular/core';
@Component({})
export class ListComponent {
@ViewChildren('item') items!: QueryList<ElementRef>;
ngAfterViewInit() {
this.items.forEach(item => console.log(item));
}
}@ViewChild('component', { read: ViewContainerRef }) container!: ViewContainerRef;
@ViewChild('template', { read: TemplateRef }) template!: TemplateRef<any>;@ViewChild(ChildComponent) child!: ChildComponent;
ngAfterViewInit() {
this.child.doSomething();
}@ViewChild('el') el!: ElementRef<HTMLElement>;
ngAfterViewInit() {
effect(() => {
if (this.shouldFocus()) {
this.el.nativeElement.focus();
}
});
}