- ViewChild is used to access a directive, child component, or a DOM element from a parent component class.
- View queries are set before the ngAfterViewInit callback is called. To write component initialization code for the references injected by @ViewChild, we have to do it inside the AfterViewInit lifecycle hook.
- We can access the DOM elements by using ElementRef available in @angular/core.
- The optional static property takes a boolean value. If true, the view query is resolved before the view and data-bound properties are fully initialized. If false, then the view query is resolved after the view and data-bound properties are completely initialized.
- If you want to access multiple children, you can use ViewChildren.
ViewChild with Child Components
child.component.html
<div>
<p>Course Name: {{CourseName}}</p>
<p>Instructor Name: {{InstructorName}}</p>
</div>
child.component.ts
import { Component, OnInit, Input, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-datepicker',
templateUrl: './datepicker.component.html',
styleUrls: ['./datepicker.component.css']
})
export class ChildComponent implements OnInit, AfterViewInit {
@Input() CourseName!: string;
@Input() InstructorName!: string ;
constructor() { }
ngAfterViewInit(): void {
throw new Error('Method not implemented.');
}
ngOnInit(): void {
}
}
app.component.html (Parent)
<app-child [CourseName]="CourseName" [InstructorName]="InstructorName">
</app-child>
app.component.ts (Parent)
import { Component } from '@angular/core';
import {ChildComponent} from './child/child.component';
import {AfterViewInit, ElementRef, ViewChild} from '@angular/core';
import { CustDirective } from './cust.directive';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit{
@ViewChild(ChildComponent) child!: ChildComponent;
CourseName: string = "Python";
InstructorName: string = "Girish";
ngAfterViewInit(){
console.log(this.child);
}
}
Course Name: Python
Instructor Name: Girish
ViewChild with DOM Elements
We can access native DOM elements with template reference variable using ViewChild.
app.component.html
<div #myText>Welcome to ViewChild DOM Element</div>
Here #myText is the TemplateReference variable
app.component.ts
import { Component } from '@angular/core';
import {ChildComponent} from './child/child.component';
import {AfterViewInit, ElementRef, ViewChild} from '@angular/core';
import { CustDirective } from './cust.directive';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit{
@ViewChild('myText', {static: false}) myText!: ElementRef;
ngAfterViewInit(){
this.myText.nativeElement.innerHTML = 'Data Updated!';
}
}
Data Updated!
ViewChild with Directives
cust.directive.ts
import { Directive,ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appCust]'
})
export class CustDirective {
constructor(private el: ElementRef) { }
color = 'yellow';
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight("");
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
app.component.ts
import { Component } from '@angular/core';
import {ChildComponent} from './child/child.component';
import {AfterViewInit, ElementRef, ViewChild} from '@angular/core';
import { CustDirective } from './cust.directive';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit{
@ViewChild(CustDirective) highlightedText!: CustDirective;
ngAfterViewInit(){
this.myText.nativeElement.innerHTML = 'Data Updated!';
}
}
app.component.html
<p appCust>Highlight me!</p>
Highlight me!
Check our other Angular Tutorials at Angular Tutorials
References
- https://angular.io/guide/attribute-directives
- https://angular.io/api/core/ViewChild
- https://angular.io/api/core/ElementRef
Learn more about Angular features in the upcoming Angular Blog articles.
Happy Learning!