From the official documentation. A ViewChild
:
Configures a view query.
View queries are set before the ngAfterViewInit callback is called.
The explanation is very minimal and I still don't quite understand what is it used for.
Consider this example from a blog I found.
Taking away the @ViewChild(TodoInputCmp)
have no effect on the code inside TodoInputCmp
Can someone give me some insight?
Thanks
ViewChildlinkProperty decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is updated.
The ViewChild decorator returns the first element that matches a given directive, component, or template reference selector.
Both ViewChild and ViewChildren are used to communicate between the components to access the data. @ViewChild and @ViewChildren are the types of decorators used to access the child component class and its different properties into the parent component. It's similar to the inheritance.
In a parent component we can use @ViewChild() for components, directives. The @ViewChild() can be also be used for template reference variable with ElementRef or TemplateRef . To use @ViewChild() we need to pass child component name or directive name or template variable as an argument.
It provides a reference to elements or components in your view:
@Component({
...
directives: [SomeComponent],
template: `
<div><span #myVar>xxx</span><div>
<some-comp></some-comp>`
})
class MyComponent {
@ViewChild('myVar') myVar:ElementRef;
@ViewChild(SomeComponent) someComponent:SomeComponent;
ngAfterViewInit() {
console.log(this.myVar.nativeElement.innerHTML);
console.log(this.someComponent);
}
}
IMPORTANT: The variables are not initialized before ngAfterViewInit()
The ViewChild
decorator is used to gain access to a child component, found in the template, so that you can access its properties and methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With