ViewChildren and ViewChild in angular
ViewChildren and ViewChild in angular:
In Angular, @ViewChild and @ViewChildren are both decorators
used to access child components, directives, or DOM elements in a component's
template.
@ViewChild queries a single child element or component in the template, providing direct access for method calls or property manipulation. It is available after view initialization, typically in the ngAfterViewInit lifecycle hook.
@ViewChildren queries multiple child elements or components and returns a QueryList, a dynamic collection that updates automatically when the DOM changes. It is useful for managing multiple similar child components.
Example:
import { Component, ViewChild, ViewChildren, QueryList, AfterViewInit, ElementRef } from '@angular/core';
import { ChildComponent } from './child/child.component'; // Assume ChildComponent is defined elsewhere
@Component({
selector: 'app-root',
template: `
<div>
<input #inputField type="text" placeholder="Enter text" />
<button (click)="focus()">Input</button>
</div>
<div>
<app-child *ngFor="let item of items" [data]="item"></app-child>
<button (click)="resetChildren()">Reset All Children</button>
</div>
`
})
export class AppComponent implements AfterViewInit {
@ViewChild('inputField') inputField!: ElementRef;
@ViewChildren(ChildComponent) childComponents!: QueryList<ChildComponent>;
items = ['Item 1', 'Item 2', 'Item 3']; // List of data to pass to child components
ngAfterViewInit() {
console.log('Input Field:', this.inputField.nativeElement);
console.log('Child Components:', this.childComponents.toArray());
}
focus() {
this.inputField.nativeElement.focus();
}
resetChildren() {
this.childComponents.toArray().forEach(child => child.reset());
}
}
Summary:
Use @ViewChild for single child access and @ViewChildren for
multiple.
@ViewChild returns a direct instance, while @ViewChildren returns a list that updates dynamically.
Comments
Post a Comment