ViewChild and ContentChild in Angular
The @ViewChild
and @ContentChild
decorators in Angular allow you to access child components, directives, or DOM elements in your component's class. These decorators are essential for component interaction and manipulation of child elements. This tutorial covers the usage of both decorators with examples.
Using ViewChild
The @ViewChild
decorator is used to access a child component, directive, or DOM element from the parent component's class. It is typically used to interact with components that are within the parent component's template.
Example with Component
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
<app-child></app-child>
<button (click)="updateChild()">Update Child</button>
`
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) child: ChildComponent;
ngAfterViewInit() {
console.log(this.child.message);
}
updateChild() {
this.child.message = 'Updated message from Parent';
}
}
@Component({
selector: 'app-child',
template: '<p>{{ message }}</p>'
})
export class ChildComponent {
message: string = 'Hello from Child';
}
Using ContentChild
The @ContentChild
decorator is used to access projected content within a component. It is typically used to interact with components or elements that are projected into the component using <ng-content>
.
Example with Projected Content
import { Component, ContentChild, AfterContentInit } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<app-child>
<p #projectedContent>This is projected content</p>
</app-child>
`
})
export class ParentComponent {}
@Component({
selector: 'app-child',
template: '<ng-content></ng-content>'
})
export class ChildComponent implements AfterContentInit {
@ContentChild('projectedContent') content: any;
ngAfterContentInit() {
console.log(this.content.nativeElement.textContent);
}
}
Key Differences
- @ViewChild: Used to access child components, directives, or DOM elements within the parent component's template.
- @ContentChild: Used to access projected content within a component.
Common Use Cases
Here are some common use cases for @ViewChild
and @ContentChild
:
- Manipulating Child Components: Use
@ViewChild
to call methods or access properties of child components. - Accessing DOM Elements: Use
@ViewChild
to access and manipulate DOM elements directly. - Projected Content: Use
@ContentChild
to access and interact with content projected into the component using<ng-content>
.
Conclusion
The @ViewChild
and @ContentChild
decorators are powerful tools for accessing and interacting with child components, directives, or DOM elements in Angular. By understanding and using these decorators effectively, you can enhance component interaction and content projection in your Angular applications. Happy coding!